问:
Object defined error - copying range till the last row of information
I'm trying to open a workbook and then select and copy a range from A7 to L7 until the last row of information (in a downward direction). I think the variable isn't properly defined. Any help?     </p>

```<code>Sub Subtotals()
Dim DT As Workbook
Dim lRowDT As Integer

Set DT = Workbooks.Open("C:\Users\ricardo\Desktop\Data Fuel.xls")
lRowDT = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Workbooks("Data Fuel.xls").Worksheets("Data").Activate
Worksheets("Data").Range("A7:L" & lRowDT).Copy

End sub
</code>```

答:
If there is not data over colums L , then this code is suitable.</p>

```<code>Sub Subtotals()
Dim DT As Workbook
Dim lRowDT As Integer
Dim Ws As Worksheet
Dim rngDB As Range, r As Long, c As Long

    Set DT = Workbooks.Open("C:\Users\ricardo\Desktop\Data Fuel.xls")
    'lRowDT = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

    Set Ws = Workbooks("Data Fuel.xls").Worksheets("Data")
    With Ws
        r = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        c = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        Set rngDB = .Range("a7", .Cells(r, "L"))
    End With
    rngDB.Copy
End Sub
</code>```

Body:
I'm trying to open a workbook and then select and copy a range from A7 to L7 until the last row of information (in a downward direction). I think the variable isn't properly defined. Any help?

Sub Subtotals()
Dim DT As Workbook
Dim lRowDT As Integer

Set DT = Workbooks.Open("C:\Users\ricardo\Desktop\Data Fuel.xls")
lRowDT = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Workbooks("Data Fuel.xls").Worksheets("Data").Activate
Worksheets("Data").Range("A7:L" & lRowDT).Copy

End sub

Body:
If there is not data over colums L , then this code is suitable.

Sub Subtotals()
Dim DT As Workbook
Dim lRowDT As Integer
Dim Ws As Worksheet
Dim rngDB As Range, r As Long, c As Long

    Set DT = Workbooks.Open("C:\Users\ricardo\Desktop\Data Fuel.xls")
    'lRowDT = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

    Set Ws = Workbooks("Data Fuel.xls").Worksheets("Data")
    With Ws
        r = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        c = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        Set rngDB = .Range("a7", .Cells(r, "L"))
    End With
    rngDB.Copy
End Sub


来源: stackexchange

问:
Base address of a process without DLL injection?
With DLL injection, grabbing the base address of the process was as easy as using

```<code>GetModuleHandleW(0);
</code>```

So I'm trying to grab the address without injection and I can't seem to get it to work. I've Googled some solutions and found others from stackoverflow but they don't seem to work. Here's what I'm using right now. I have the right headers and it compiles. It just doesn't work.

```<code>DWORD_PTR dwGetModuleBaseAddress(DWORD dwProcID, TCHAR *szModuleName)
{
    DWORD_PTR dwModuleBaseAddress = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwProcID);
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32;
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                if (_tcsicmp(ModuleEntry32.szModule, szModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}
</code>```

I try to cout this address and it just gives me 0. I think it might be the fact that I don't understand the second parameter. I'm just copying what I saw. Here's my main function.

```<code>int main() {
   HWND hwnd = FindWindowA(NULL, gameName);
   int x;
   if (hwnd == NULL) {
      cout << "Cannot find " << (string)gameName << " window" << endl;
      cin >> x;
      exit(-1);
   }

   DWORD procID;
   GetWindowThreadProcessId(hwnd, &procID);
   HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);

   DWORD playerAddr = 0;
   playerAddr = dwGetModuleBaseAddress(procID, _T("starbound.exe"));
   cout << hex << playerAddr;
}
</code>```

Some of this may be redundant because I'm just adding it to what I had before. I'm just not sure why it's not working.

答:
If you use your dwModuleBaseAddress as a debug tool, it may be easier to spot the call that fails...

```<code>DWORD_PTR dwGetModuleBaseAddress(DWORD dwProcID, TCHAR *szModuleName)
{
    DWORD_PTR dwModuleBaseAddress = (DWORD_PTR)-1; // unlikely value...
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwProcID);
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32;
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);

        dwModuleBaseAddress = (DWORD_PTR)-2;

        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                --dwModuleBaseAddress;
                if (_tcsicmp(ModuleEntry32.szModule, szModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}
</code>```

You can also check the error that caused the issue using GetLastError()

```<code>void PrintLastError()
{
    LPTSTR psz;
    DWORD dwError = GetLastError();
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        0,
        (LPTSTR)&psz,
        1024,
        NULL);

    _tprintf(_T("Windows reports error: (0x%08X): %s\n"), dwError, (psz) ? psz : _T("(null)"));
    if (psz)
    {
        LocalFree(psz);
    }
}
</code>```

If all else fails, try running this example from msdn https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms686849(v=vs.85).aspx

It will print the exact string you want to match, the problem may come from  there.

ContentLicense: CC BY-SA 3.0

Body:
With DLL injection, grabbing the base address of the process was as easy as using

GetModuleHandleW(0);

So I'm trying to grab the address without injection and I can't seem to get it to work. I've Googled some solutions and found others from stackoverflow but they don't seem to work. Here's what I'm using right now. I have the right headers and it compiles. It just doesn't work.

DWORD_PTR dwGetModuleBaseAddress(DWORD dwProcID, TCHAR *szModuleName)
{
    DWORD_PTR dwModuleBaseAddress = 0;
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwProcID);
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32;
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                if (_tcsicmp(ModuleEntry32.szModule, szModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}

I try to cout this address and it just gives me 0. I think it might be the fact that I don't understand the second parameter. I'm just copying what I saw. Here's my main function.

int main() {
   HWND hwnd = FindWindowA(NULL, gameName);
   int x;
   if (hwnd == NULL) {
      cout << "Cannot find " << (string)gameName << " window" << endl;
      cin >> x;
      exit(-1);
   }

   DWORD procID;
   GetWindowThreadProcessId(hwnd, &procID);
   HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);

   DWORD playerAddr = 0;
   playerAddr = dwGetModuleBaseAddress(procID, _T("starbound.exe"));
   cout << hex << playerAddr;
}

Some of this may be redundant because I'm just adding it to what I had before. I'm just not sure why it's not working.

Body:
If you use your dwModuleBaseAddress as a debug tool, it may be easier to spot the call that fails...

DWORD_PTR dwGetModuleBaseAddress(DWORD dwProcID, TCHAR *szModuleName)
{
    DWORD_PTR dwModuleBaseAddress = (DWORD_PTR)-1; // unlikely value...
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, dwProcID);
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32;
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);

        dwModuleBaseAddress = (DWORD_PTR)-2;

        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                --dwModuleBaseAddress;
                if (_tcsicmp(ModuleEntry32.szModule, szModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}

You can also check the error that caused the issue using GetLastError()

void PrintLastError()
{
    LPTSTR psz;
    DWORD dwError = GetLastError();
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        0,
        (LPTSTR)&psz,
        1024,
        NULL);

    _tprintf(_T("Windows reports error: (0x%08X): %s\n"), dwError, (psz) ? psz : _T("(null)"));
    if (psz)
    {
        LocalFree(psz);
    }
}

If all else fails, try running this example from msdn https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms686849(v=vs.85).aspx

It will print the exact string you want to match, the problem may come from  there.


问:
In Android Textview within a Scrollview, not displaying all the text(which it gets from strings.xml)
I am developing a game and need a popup for the rules. I write the text in the string.xml file and display in a textview within a Scrollview, but all the Text is not getting displayed. Only the last few lines of the text is getting displayed. Please help me!!

Here is the layout popup xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/dialogbg1"
android:gravity="center"
android:id="@+id/howto"
android:orientation="vertical">

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/scrollView"
    android:layout_gravity="right"
    android:layout_weight="1"
    android:nestedScrollingEnabled="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/rule"
        android:layout_gravity="center"
        android:textColor="#fffff7f4"
        android:id="@+id/rules"
        android:textStyle="italic"
        android:outlineProvider="paddedBounds" />
</ScrollView>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/done"
    android:id="@+id/done"
    android:layout_marginTop="5dp"
    android:layout_weight="1"
    android:textColor="#fffff7f4"
    android:background="@drawable/buttbg1"
    android:clickable="true"/>
</code>```

and the "rule" variable in the strings.xml file

```<code><string name="rule">Rules to play Mancala!!!\n\nMancala is an ancient family of board games, and there are numerous variants.\n
    This is a version of the basic game, known as two-rank Mancala and also known as Kalah.\n
    1.The Mancala board is made up of two rows of six holes, or pits, each.\n\n
    2.Four playing pieces are placed in each of the 12 holes.\n\n
    3.Each player has a store to the right side of the Mancala board.\n\n
    4.The game begins with one player picking up all of the pieces in any one of the holes on his side.\n\n
    5.Moving counter clockwise, the player deposits one of the stones in each hole until the stones run out.\n\n
    6.If you run into your own store, deposit one piece in it. If you run into your opponent\'s store, skip it.\n\n
    7.If the last piece you drop is in your own store, you get a free turn.\n\n
    8.If the last piece you drop is in an empty hole on your side, you capture that piece and any pieces in the hole directly opposite.\n\n
    9.Always place all captured pieces in your store.\n\n
    10.The game ends when all six spaces on one side of the Mancala board are empty.\n\n
    11.The player who still has pieces on his side of the board when the game ends captures all of those pieces.\n\n
    12.Count all the pieces in each store. The winner is the player with the most pieces.</string>
</code>```

I'm not able to figure out why all the text is not getting displayed. only text from 4 is getting displayed. If I change the layout screensize, then it gets displayed from 3. Please help me!!!

答:
Inside your TextView Tag Use :  </p>

```<code>android:layout_gravity="top"
</code>```

Body:
I am developing a game and need a popup for the rules. I write the text in the string.xml file and display in a textview within a Scrollview, but all the Text is not getting displayed. Only the last few lines of the text is getting displayed. Please help me!!

Here is the layout popup xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/dialogbg1"
android:gravity="center"
android:id="@+id/howto"
android:orientation="vertical">

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/scrollView"
    android:layout_gravity="right"
    android:layout_weight="1"
    android:nestedScrollingEnabled="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/rule"
        android:layout_gravity="center"
        android:textColor="#fffff7f4"
        android:id="@+id/rules"
        android:textStyle="italic"
        android:outlineProvider="paddedBounds" />
</ScrollView>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/done"
    android:id="@+id/done"
    android:layout_marginTop="5dp"
    android:layout_weight="1"
    android:textColor="#fffff7f4"
    android:background="@drawable/buttbg1"
    android:clickable="true"/>

and the "rule" variable in the strings.xml file

<string name="rule">Rules to play Mancala!!!\n\nMancala is an ancient family of board games, and there are numerous variants.\n
    This is a version of the basic game, known as two-rank Mancala and also known as Kalah.\n
    1.The Mancala board is made up of two rows of six holes, or pits, each.\n\n
    2.Four playing pieces are placed in each of the 12 holes.\n\n
    3.Each player has a store to the right side of the Mancala board.\n\n
    4.The game begins with one player picking up all of the pieces in any one of the holes on his side.\n\n
    5.Moving counter clockwise, the player deposits one of the stones in each hole until the stones run out.\n\n
    6.If you run into your own store, deposit one piece in it. If you run into your opponent\'s store, skip it.\n\n
    7.If the last piece you drop is in your own store, you get a free turn.\n\n
    8.If the last piece you drop is in an empty hole on your side, you capture that piece and any pieces in the hole directly opposite.\n\n
    9.Always place all captured pieces in your store.\n\n
    10.The game ends when all six spaces on one side of the Mancala board are empty.\n\n
    11.The player who still has pieces on his side of the board when the game ends captures all of those pieces.\n\n
    12.Count all the pieces in each store. The winner is the player with the most pieces.</string>

I'm not able to figure out why all the text is not getting displayed. only text from 4 is getting displayed. If I change the layout screensize, then it gets displayed from 3. Please help me!!!

Body:
Inside your TextView Tag Use :

android:layout_gravity="top"


问:
Matplotlib imshow in Pycharm Ipython not always displaying image
I'm using Pycharm IDE for Ipython and like it a lot. However, recently I'm having trouble with the matplotlib pyplot imshow function. Sometimes it works properly and displays an image but other times it just hangs (the cell is not executed, its labeled by the asterisk). You can execute additional cells after this with the image never being displayed. Im on OS X mavericks, using pycharm 5, latest ipython and matplotlib versions, enthought canopy python 2.7.. anyone experiencing something similar and worked out a solution? </p>

答:
The code might be helpful:</p>

```<code>import matplotlib.pyplot as plt
plt.imshow(im)
plt.show()
</code>```

Body:
The code might be helpful:

import matplotlib.pyplot as plt
plt.imshow(im)
plt.show()


问:
Efficient reformatting of ring buffer (circular buffer) to continous array
I've successfully implemented a function that copies an arbitrary amount of values starting from an arbitrary point in a ring buffer to a continuous array but I would like to make it more efficient. Here's a minimum example of my code:

```<code>#include <string.h>
#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

/*Foo: a function*/
void Foo(int * print_array, int print_amount){
    /*Simulate overhead*/
    this_thread::sleep_for(chrono::microseconds(1000));
    int sum = 0;
    for (int i = 0; i < print_amount; i++){
        sum += print_array[i];          //Linear operation
//      cout << print_array[i] << " "; //Uncomment to check if correct funtionality
    }
}

/*Example function*/
int main(){
    /*Initialze ring buffer*/
    int ring_buffer_elements = 32;                              //A largeish size
    int ring_buffer_size = ring_buffer_elements * sizeof(int);
    int * ring_buffer = (int *) malloc(ring_buffer_size);
    for (int i = 0; i < ring_buffer_elements; i++)
        ring_buffer[i] = i;                                     //Fill buffer with ordered numbers

    /*Initialze array*/
    int array_elements = 16;                                    //A smaller largeish size
    int array_size = array_elements * sizeof(int);
    int * array = (int *) malloc(array_size);

    /*Set reference pointers*/
    int * start_pointer = ring_buffer;
    int * end_pointer = ring_buffer + ring_buffer_elements;

    /*Set moving copy pointer*/
    int * copy_pointer = start_pointer;

    /*Set "random" amount to be copied at each iteration*/
    int copy_amount = 11;

    /*Set loop amount to check functionality or run time*/
    int loop_amount = 1000;                                 //Set lower if checking functionality

    /***WORKING METHOD***/
    /*Start timer*/
    auto start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Copy loop*/
        for (int j = 0; j < copy_amount; j++){
            array[j] = *copy_pointer;           //Copy value from ring buffer
            copy_pointer++;                     //Move pointer
            if (copy_pointer >= end_pointer)
                copy_pointer = start_pointer;   //Reset pointer if reached end of ring buffer
        }
        Foo(array, copy_amount);    //Call a function
    }

    /*Check run time*/
    chrono::duration<double> run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    double run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

/***NAIVE METHOD***/
    /*Reset moving pointer*/
    copy_pointer = start_pointer;

    /*Start timer*/
    start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Compute how many elements must be copied after reaching end of ring buffer*/
        int copy_remainder = copy_pointer + copy_amount - end_pointer; //Ugly pointer arithmetic?
        /*Check if we need to loop back or not*/
        if (copy_remainder <= 0){
            Foo(copy_pointer, copy_amount); //Call function
            copy_pointer += copy_amount;    //Move pointer
        } else {
            Foo(copy_pointer, copy_amount-copy_remainder);  //Call function with part of values from copy pointer
            Foo(start_pointer, copy_remainder);             //Call function with remainder of values from start of ring buffer
            copy_pointer = start_pointer + copy_remainder;  //Move pointer
        }
    }

    /*Check run time*/
    run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

    /***memcpy METHOD***/
    /*Reset moving pointer*/
    copy_pointer = start_pointer;

    /*Initialize size reference*/
    int int_size = (int) sizeof(int);

    /*Start timer*/
    start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Compute how many elements must be copied after reaching end of ring buffer*/
        int copy_remainder = copy_pointer + copy_amount - end_pointer; //Ugly pointer arithmetic?
        /*Check if we need to loop back or not*/
        if (copy_remainder <= 0){
            memcpy(array, copy_pointer, copy_amount*int_size);  //Use memcpy
            copy_pointer += copy_amount;                        //Move pointer
        } else {
            memcpy(array, copy_pointer, (copy_amount-copy_remainder)*int_size);                 //Use memcpy with part of values from copy pointer
            memcpy(array+(copy_amount-copy_remainder), start_pointer, copy_remainder*int_size); //Use memcpy wih remainder of values from start of ring buffer
            copy_pointer = start_pointer + copy_remainder;                                      //Move pointer
        }
        /*Call a function*/
        Foo(array, copy_amount);
    }

    /*Check run time*/
    run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

}
</code>```

The ring buffer is used for a continuously updating stream of audio data and thus the amount of latency introduced must be kept to a minimum, why I'm trying to improve it.

I was thinking that copying the values in WORKING METHOD is redundant and that it should be possible to just pass through the original ring buffer data. My naive approach of doing this was to write with the original data and  whenever the data looped back write again (see NAIVE IMPROVEMENT).

Indeed, in this minimum example this improvement is orders of magnitude quicker. However, in my real application Foo is replaced with a function that writes to a hardware buffer and has quite a overhead ̣̣̣̣̣- the end result is slower than the WORKING METHOD code, meaning that I never should use it (or Foo in this case) more than once (per time to write audio data). (EDIT a simulated overhead was added to Foo to accurately depict this issue).

My question is therefore if there is a quicker way to copy data from a ring buffer to a single, continuous array?

(Also, the ring buffer will never need to loop back more than once per time to write: copy_amount is always less than ring_buffer_elements)

Thanks!

EDIT
Replaced original code snippet with minimum example as per Passer By's suggestion.

EDIT 2
Added a simulated overhead and an memcpy as per duong_dajgja's suggestion. In the example the memcpy method and the working method has essentially the same performance (with the latter having somewhat of an edge). In my application memcpy is about 3-4 % quicker than the working method when using the smallest buffer possible. So quicker, but regrettably far from significant.

答:
I would like to suggest a ring buffer - like structure that is actually an array.

Since your data is audio stream so I suppose that data would come in order (e.g. time-series data).

Assume the buff has capacity of 100 elements. Once the buff gets full and you want to add a new element to the end, you first have to left-shift region from buff[1] to buff[99] by one using memmove then simply put the new element at buff[99]. Doing so you are sure that your ring buffer is always an array with correct order (from buff[0] to buff[99]). Now, simply memcpy whole region from buff[0] to buff[99] to the destination array as you desire.

Body:
I've successfully implemented a function that copies an arbitrary amount of values starting from an arbitrary point in a ring buffer to a continuous array but I would like to make it more efficient. Here's a minimum example of my code:

#include <string.h>
#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

/*Foo: a function*/
void Foo(int * print_array, int print_amount){
    /*Simulate overhead*/
    this_thread::sleep_for(chrono::microseconds(1000));
    int sum = 0;
    for (int i = 0; i < print_amount; i++){
        sum += print_array[i];          //Linear operation
//      cout << print_array[i] << " "; //Uncomment to check if correct funtionality
    }
}

/*Example function*/
int main(){
    /*Initialze ring buffer*/
    int ring_buffer_elements = 32;                              //A largeish size
    int ring_buffer_size = ring_buffer_elements * sizeof(int);
    int * ring_buffer = (int *) malloc(ring_buffer_size);
    for (int i = 0; i < ring_buffer_elements; i++)
        ring_buffer[i] = i;                                     //Fill buffer with ordered numbers

    /*Initialze array*/
    int array_elements = 16;                                    //A smaller largeish size
    int array_size = array_elements * sizeof(int);
    int * array = (int *) malloc(array_size);

    /*Set reference pointers*/
    int * start_pointer = ring_buffer;
    int * end_pointer = ring_buffer + ring_buffer_elements;

    /*Set moving copy pointer*/
    int * copy_pointer = start_pointer;

    /*Set "random" amount to be copied at each iteration*/
    int copy_amount = 11;

    /*Set loop amount to check functionality or run time*/
    int loop_amount = 1000;                                 //Set lower if checking functionality

    /***WORKING METHOD***/
    /*Start timer*/
    auto start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Copy loop*/
        for (int j = 0; j < copy_amount; j++){
            array[j] = *copy_pointer;           //Copy value from ring buffer
            copy_pointer++;                     //Move pointer
            if (copy_pointer >= end_pointer)
                copy_pointer = start_pointer;   //Reset pointer if reached end of ring buffer
        }
        Foo(array, copy_amount);    //Call a function
    }

    /*Check run time*/
    chrono::duration<double> run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    double run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

/***NAIVE METHOD***/
    /*Reset moving pointer*/
    copy_pointer = start_pointer;

    /*Start timer*/
    start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Compute how many elements must be copied after reaching end of ring buffer*/
        int copy_remainder = copy_pointer + copy_amount - end_pointer; //Ugly pointer arithmetic?
        /*Check if we need to loop back or not*/
        if (copy_remainder <= 0){
            Foo(copy_pointer, copy_amount); //Call function
            copy_pointer += copy_amount;    //Move pointer
        } else {
            Foo(copy_pointer, copy_amount-copy_remainder);  //Call function with part of values from copy pointer
            Foo(start_pointer, copy_remainder);             //Call function with remainder of values from start of ring buffer
            copy_pointer = start_pointer + copy_remainder;  //Move pointer
        }
    }

    /*Check run time*/
    run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

    /***memcpy METHOD***/
    /*Reset moving pointer*/
    copy_pointer = start_pointer;

    /*Initialize size reference*/
    int int_size = (int) sizeof(int);

    /*Start timer*/
    start_time = chrono::high_resolution_clock::now();

    /*"Continuous" loop*/
    for (int i = 0; i < loop_amount; i++){
        /*Compute how many elements must be copied after reaching end of ring buffer*/
        int copy_remainder = copy_pointer + copy_amount - end_pointer; //Ugly pointer arithmetic?
        /*Check if we need to loop back or not*/
        if (copy_remainder <= 0){
            memcpy(array, copy_pointer, copy_amount*int_size);  //Use memcpy
            copy_pointer += copy_amount;                        //Move pointer
        } else {
            memcpy(array, copy_pointer, (copy_amount-copy_remainder)*int_size);                 //Use memcpy with part of values from copy pointer
            memcpy(array+(copy_amount-copy_remainder), start_pointer, copy_remainder*int_size); //Use memcpy wih remainder of values from start of ring buffer
            copy_pointer = start_pointer + copy_remainder;                                      //Move pointer
        }
        /*Call a function*/
        Foo(array, copy_amount);
    }

    /*Check run time*/
    run_time_ticks = chrono::high_resolution_clock::now() - start_time;
    run_time = run_time_ticks.count();

    /*Print result*/
    cout << endl << run_time << endl;

}

The ring buffer is used for a continuously updating stream of audio data and thus the amount of latency introduced must be kept to a minimum, why I'm trying to improve it.

I was thinking that copying the values in WORKING METHOD is redundant and that it should be possible to just pass through the original ring buffer data. My naive approach of doing this was to write with the original data and  whenever the data looped back write again (see NAIVE IMPROVEMENT).

Indeed, in this minimum example this improvement is orders of magnitude quicker. However, in my real application Foo is replaced with a function that writes to a hardware buffer and has quite a overhead ̣̣̣̣̣- the end result is slower than the WORKING METHOD code, meaning that I never should use it (or Foo in this case) more than once (per time to write audio data). (EDIT a simulated overhead was added to Foo to accurately depict this issue).

My question is therefore if there is a quicker way to copy data from a ring buffer to a single, continuous array?

(Also, the ring buffer will never need to loop back more than once per time to write: copy_amount is always less than ring_buffer_elements)

Thanks!

EDIT
Replaced original code snippet with minimum example as per Passer By's suggestion.

EDIT 2
Added a simulated overhead and an memcpy as per duong_dajgja's suggestion. In the example the memcpy method and the working method has essentially the same performance (with the latter having somewhat of an edge). In my application memcpy is about 3-4 % quicker than the working method when using the smallest buffer possible. So quicker, but regrettably far from significant.


问:
Session issue with unset() and the browser back button
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

```<code>// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);
</code>```

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.

答:
Are you sure the session itself isn't being flushed on the server-side?  I had a situation in a shared-hosting environment where the server settings were caused my sessions to disappear.  I had to add local settings in my app to overcome this (private rather than common session storage).

These are the settings I have in my .htaccess file for the sessions, giving them reasonable time on the disk

```<code>php_value session.gc_probability 1
php_value session.gc_divisor 100
php_value session.gc_maxlifetime 3600
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.

Body:
Are you sure the session itself isn't being flushed on the server-side?  I had a situation in a shared-hosting environment where the server settings were caused my sessions to disappear.  I had to add local settings in my app to overcome this (private rather than common session storage).

These are the settings I have in my .htaccess file for the sessions, giving them reasonable time on the disk

php_value session.gc_probability 1
php_value session.gc_divisor 100
php_value session.gc_maxlifetime 3600


问:
Delete first character from a text file

I have a text file in which the first character - I want to delete, but I am not getting either its a CR or LF character, how Can I delete the file character from the entire file.

答:
Use the tail command:

```<code>tail -c +2 file.txt > newfile.txt
</code>```

The -c option says to count by characters rather than lines, and +2 means to output the tail starting from character 2.

Title: Delete first character from a text file

Body:
Use the tail command:

tail -c +2 file.txt > newfile.txt

The -c option says to count by characters rather than lines, and +2 means to output the tail starting from character 2.


问:
IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"
What are common causes for IntelliJ IDEA not being able to resolve built-in JVM types and methods? For example, when I mouse over String the tooltip says "Cannot resolve symbol 'String'". It's as if IntelliJ has doesn't know where the JVM is.

By the way, I am running OS X 10.6.6. Everything was working fine until I ran the system update this morning.

答:
For me, IntelliJ could autocomplete packages, but never seemed to admit there were actual classes at any level of the hierarchy. Neither re-choosing the SDK nor re-creating the project seemed to fix it.

What did fix it was to delete the per-user IDEA directory ( in my case ~/.IntelliJIdea2017.1/) which meant losing all my other customizations... But at least it made the issue go away.

ContentLicense: CC BY-SA 4.0


问:
REST API calls not working in swift
I'm following this tutorial for making a simple REST API call in swift: https://grokswift.com/simple-rest-with-swift/

The problem I'm running into is that the data task completion handler next gets executed. When I'm debugging it step by step, it just jumps over the completion handler block. Nothing is printed in the console, either.

I've searched for other methods of making REST API calls, but they are all very similar to this one and not working, either.

Here is my code:

```<code>    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
    guard let url = URL(string: endpoint) else {
        return
    }
    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        guard error == nil else {
            print("Error calling GET")
            return
        }
        guard let responseData = data else {
            print("Error receiving data")
            return
        }
        do {
            print ("Parsing response...")
        }
    }
    task.resume()
</code>```

答:
Why you dont use this Library Alamofire is an HTTP networking library written in Swift.

Add this line to your Podfile

```<code>    pod 'Alamofire', '~> 4.4'
</code>```

Then, run the following command:

```<code>    pod install
</code>```

Then in your ViewController file:

import Alamofire

```<code>Alamofire.request("https://jsonplaceholder.typicode.com/todos/1").responseJSON { response in

     print("Request: \(String(describing: response.request))")   // original url request
     print("Response: \(String(describing: response.response))") // http url response
     print("Result: \(response.result)")                         // response serialization result

     if let json = response.result.value {
        print("JSON: \(json)") // serialized json response
     }

     If let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
       print("Data: \(utf8Text)") // original server data as UTF8 string
     }
}
</code>```

And in here are an example of how to parse the result.

https://github.com/CristianCardosoA/JSONParser

For more info about Alamofire:

https://github.com/Alamofire/Alamofire

I hope this help.

Title: REST API calls not working in swift

Body:
I'm following this tutorial for making a simple REST API call in swift: https://grokswift.com/simple-rest-with-swift/

The problem I'm running into is that the data task completion handler next gets executed. When I'm debugging it step by step, it just jumps over the completion handler block. Nothing is printed in the console, either.

I've searched for other methods of making REST API calls, but they are all very similar to this one and not working, either.

Here is my code:

    let endpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
    guard let url = URL(string: endpoint) else {
        return
    }
    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest) { (data, response, error) -> Void in
        guard error == nil else {
            print("Error calling GET")
            return
        }
        guard let responseData = data else {
            print("Error receiving data")
            return
        }
        do {
            print ("Parsing response...")
        }
    }
    task.resume()

Body:
Why you dont use this Library Alamofire is an HTTP networking library written in Swift.

Add this line to your Podfile

    pod 'Alamofire', '~> 4.4'

Then, run the following command:

    pod install

Then in your ViewController file:

import Alamofire

Alamofire.request("https://jsonplaceholder.typicode.com/todos/1").responseJSON { response in

     print("Request: \(String(describing: response.request))")   // original url request
     print("Response: \(String(describing: response.response))") // http url response
     print("Result: \(response.result)")                         // response serialization result

     if let json = response.result.value {
        print("JSON: \(json)") // serialized json response
     }

     If let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
       print("Data: \(utf8Text)") // original server data as UTF8 string
     }
}

And in here are an example of how to parse the result.

https://github.com/CristianCardosoA/JSONParser

For more info about Alamofire:

https://github.com/Alamofire/Alamofire

I hope this help.


问:
Error in PDO/PHP code when connecting to database
I am trying to use PHP and PDO in order to create and connect to the MySQL database I have already created.  Everything is working fine except that I keeps giving me this error:

Connection failed:PDO::__construct(): SQLSTATE[HY000]: General error: invalid error mode

Can someone please tell me what this error means. Thanks.

EDIT: Here is the draft code.

This is connection.php

```<code><?php
class Config
{
    public function Con()
    {
        $config = new Config();
    }
}
class Connection
{
    protected $db = null;
    public function Open()
    {
        try {
            $dsn = "mysql:dbname=cashgroup;
            host=localhost";
            $user = "root";
            $password = "newpassword";
            $options = array(PDO::ATTR_ERRMODE =>
            PDO::ATTR_DEFAULT_FETCH_MODE
            );

            $this -> db = new PDO($dsn, $user, $password,      $options);

            return $this -> db;
            } catch (PDOException $e) {
                echo 'Connection failed:' . $e ->getMessage();
            }
        }
        public function Closed()
        {
            $this -> db = null;
             return true;
        }
}
?>
</code>```

and this is include.php

```<code><?php
 include 'connection.php';

try {
    $conec = new Connection();
    $con = $conec -> Open();
    if ($con) {
        echo 'connected';
        $sql = "INSERT INTO `clients`(`name`, `email`) VALUES    (`FakeName`, `fakeemail@gmail.com`)";
        $re = $con -> query($sql);
    } else {
        echo $con;
    }
 }

catch (PDOException $ex) {
    echo $ex -> getMessage();
}
?>
</code>```

答:
You've messed up the attributes here:

```<code>$options = array(PDO::ATTR_ERRMODE =>
   PDO::ATTR_DEFAULT_FETCH_MODE
);
</code>```

They should be something like this:

```<code>$options = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
</code>```

Or any other valid values.

Body:
I am trying to use PHP and PDO in order to create and connect to the MySQL database I have already created.  Everything is working fine except that I keeps giving me this error:

Connection failed:PDO::__construct(): SQLSTATE[HY000]: General error: invalid error mode

Can someone please tell me what this error means. Thanks.

EDIT: Here is the draft code.

This is connection.php

<?php
class Config
{
    public function Con()
    {
        $config = new Config();
    }
}
class Connection
{
    protected $db = null;
    public function Open()
    {
        try {
            $dsn = "mysql:dbname=cashgroup;
            host=localhost";
            $user = "root";
            $password = "newpassword";
            $options = array(PDO::ATTR_ERRMODE =>
            PDO::ATTR_DEFAULT_FETCH_MODE
            );

            $this -> db = new PDO($dsn, $user, $password,      $options);

            return $this -> db;
            } catch (PDOException $e) {
                echo 'Connection failed:' . $e ->getMessage();
            }
        }
        public function Closed()
        {
            $this -> db = null;
             return true;
        }
}
?>

and this is include.php

<?php
 include 'connection.php';

try {
    $conec = new Connection();
    $con = $conec -> Open();
    if ($con) {
        echo 'connected';
        $sql = "INSERT INTO `clients`(`name`, `email`) VALUES    (`FakeName`, `fakeemail@gmail.com`)";
        $re = $con -> query($sql);
    } else {
        echo $con;
    }
 }

catch (PDOException $ex) {
    echo $ex -> getMessage();
}
?>

Body:
You've messed up the attributes here:

$options = array(PDO::ATTR_ERRMODE =>
   PDO::ATTR_DEFAULT_FETCH_MODE
);

They should be something like this:

$options = array(
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);

Or any other valid values.


问:
ScrollView/TextView not displaying all data when layout_gravity is set
Whenever the android:layout_gravity="bottom" attribute is set on the style xml sheet, the text seems to be cut off at the top, and extra blank lines appear at the bottom. I have set this in order to auto-scroll to the bottom when there is too much text to display. This is hosted in a DialogFragment.

Note: the text being displayed is from TextView.setText(Html.fromHtml()), with newlines being done as
 if that matters. The a's printed are just test data.

On debugging the TextView, it appears the data is there (in the mText variable), but it just doesn't display.

Dialog xml sheet:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:fillViewport="true" >

        <TextView android:id="@+id/status_olcr_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom" />

</ScrollView>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="?android:attr/buttonBarStyle" >

    <Button
        android:id="@+id/status_olcr_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/ok"
        style="?android:attr/buttonBarButtonStyle"
        android:clickable="false" />

</LinearLayout>
</code>```

On screen display of what is happening (but shouldn't):

And this is what should be happening (when there is no layout_gravity attribute):

Any idea of whats happening?

Update: I have turned on 'Show layout margins' and the TextView is rendered above the ScrollView bounds (or other way around).. See below images:

答:
Inside textView Tag use :</p>

```<code>android:layout_gravity="top"
</code>```

Body:
Whenever the android:layout_gravity="bottom" attribute is set on the style xml sheet, the text seems to be cut off at the top, and extra blank lines appear at the bottom. I have set this in order to auto-scroll to the bottom when there is too much text to display. This is hosted in a DialogFragment.

Note: the text being displayed is from TextView.setText(Html.fromHtml()), with newlines being done as
 if that matters. The a's printed are just test data.

On debugging the TextView, it appears the data is there (in the mText variable), but it just doesn't display.

Dialog xml sheet:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:fillViewport="true" >

        <TextView android:id="@+id/status_olcr_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom" />

</ScrollView>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="?android:attr/buttonBarStyle" >

    <Button
        android:id="@+id/status_olcr_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/ok"
        style="?android:attr/buttonBarButtonStyle"
        android:clickable="false" />

</LinearLayout>

On screen display of what is happening (but shouldn't):

And this is what should be happening (when there is no layout_gravity attribute):

Any idea of whats happening?

Update: I have turned on 'Show layout margins' and the TextView is rendered above the ScrollView bounds (or other way around).. See below images:

Body:
Inside textView Tag use :

android:layout_gravity="top"


问:
Move buttons to the bottom right corner of the header
I am trying to create a basic webpage.  I want to have buttons at the top for logging in or signing up, but I can't seem to get them to move to the bottom right of the header no matter what I do.  They usually just end up in the center, and I tried to float them but that definitely didn't work.  What's a good way to go about styling buttons in CSS?

HTML:

    .clear {
 clear: both;
    }

    #container{
        margin: 0 auto;
        max-width: 1200px;
    }
    header {
        width: 94%;
        padding: 3%;
        background-color: #F3D22D;
    }
    header #title {
        font-size: 50px;
        color: #fff;
    }
    nav {
        width: 97%;
        background-color: #DDCFC5;
        padding: 0 1.5% 0 1.5%;
    }
    nav ul li {
        display: inline-block;
        padding: 15px 1.5% 15px 1.5% ;
    }
    nav ul li a {
        text-decoration: none;
        color: #ffffff;
        font-size: 1.2em;
    }
     nav ul li a:hover {
         color: #000000;
         text-decoration: none;
     }
     #content {
        float: left;
        padding: 3%;
        width: 64%;
    }
    aside {
        float: right;
        padding: 3%;
        width: 24%;
        background-color: #DDCFC5;
    }
    footer{
        width: 94%;
        padding: 3%;
        background-color: #F3D22D;
        border-top: 5px solid #DDCFC5;
        color: #fff;
        text-align: center;
    }
    @media all and (max-width : 768px) {
        header {
            text-align: center;
        }
        nav {
            text-align: center;
        }
        #content {
            width: 94%;
            padding: 3%;
        }
        #sidebar {
            width: 94%;
            padding: 3%;
            border-top: 3px solid #E64A19;
        }
    }
    @media all and (max-width : 330px) {
        nav ul li {
            display:block;
            width: 94%;
        }
    }

    button {
     background-color: #4CAF50;
     border: none;
     color: white;
     padding: 15px 32px;
     text-align: center;
     text-decoration: none;
     display: inline-block;
     font-size: 16px;
     margin: 4px 2px;
     cursor: pointer;
    }

    #usermenu {
     bottom: 0;
     left: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html>
     <head>
  <title>Website</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link type="text/css? rel="stylesheet" href="reset.css" />
  <link type="text/css" rel="stylesheet" href="style.css" />
 </head>
 <body>
  <div id="container">
   <!-- header -->
   <header id="header">
    <h1 id="title">Website</h1>
    <div id="usermenu">
     <button  type="button">Login</button>
     <button type="button">Sign Up</button>
    </div>
   </header>
   <!-- navigation -->
   <nav id="menu" class="clearfix">
    <ul>
     <li>Home</li>
     <li>About</li>
     <li>Contact</li>
    </ul>
   </nav>

       <!-- main content area -->

       <section id="content">
        <h2>Built with HTML5 and CSS3</h2>
        <p>
         More content here................
         <br>
         Hello... blah blahblah
        </p>
       </section>

       <!-- sidebar -->
       <aside id="sidebar">
        <h3>This is the sidebar</h3>
        <p>content goes here...</p>
       </aside>
       <div class="clear"></div>
       <!-- footer -->
       <footer id="footer" class="clearfix">
        Copyright &copy Gregory Soble 2017
       </footer>
      </div>
     </body>
    </html></code>```

答:
By default the position of an element is static, so values for top, right, bottom, and left have no effect at all.  You need to give the element/elements another value for position to be able to "position" them.

.clear {
clear: both;
}

#container{
    margin: 0 auto;
    max-width: 1200px;
}
header {
    position: relative;
    width: 94%;
    padding: 3%;
    background-color: #F3D22D;
}
header #title {
    font-size: 50px;
    color: #fff;
}
nav {
    width: 97%;
    background-color: #DDCFC5;
    padding: 0 1.5% 0 1.5%;
}
nav ul li {
    display: inline-block;
    padding: 15px 1.5% 15px 1.5% ;
}
nav ul li a {
    text-decoration: none;
    color: #ffffff;
    font-size: 1.2em;
}
 nav ul li a:hover {
     color: #000000;
     text-decoration: none;
 }
 #content {
    float: left;
    padding: 3%;
    width: 64%;
}
aside {
    float: right;
    padding: 3%;
    width: 24%;
    background-color: #DDCFC5;
}
footer{
    width: 94%;
    padding: 3%;
    background-color: #F3D22D;
    border-top: 5px solid #DDCFC5;
    color: #fff;
    text-align: center;
}
@media all and (max-width : 768px) {
    header {
        text-align: center;
    }
    nav {
        text-align: center;
    }
    #content {
        width: 94%;
        padding: 3%;
    }
    #sidebar {
        width: 94%;
        padding: 3%;
        border-top: 3px solid #E64A19;
    }
}
@media all and (max-width : 330px) {
    nav ul li {
        display:block;
        width: 94%;
    }
}

button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

#usermenu {
    position: absolute;
    bottom: 0;
    right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="container">
        <!-- header -->
        <header id="header">
            <h1 id="title">Website</h1>
            <div id="usermenu">
                <button  type="button">Login</button>
                <button type="button">Sign Up</button>
            </div>
        </header>
        <!-- navigation -->
        <nav id="menu" class="clearfix">
            <ul>
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
            </ul>
        </nav>

            <!-- main content area -->

            <section id="content">
                <h2>Built with HTML5 and CSS3</h2>
                <p>
                    More content here................
                    <br>
                    Hello... blah blahblah
                </p>
            </section>

            <!-- sidebar -->
            <aside id="sidebar">
                <h3>This is the sidebar</h3>
                <p>content goes here...</p>
            </aside>
            <div class="clear"></div>
            <!-- footer -->
            <footer id="footer" class="clearfix">
                Copyright &copy Gregory Soble 2017
            </footer>
        </div></code>```

Body:
I am trying to create a basic webpage.  I want to have buttons at the top for logging in or signing up, but I can't seem to get them to move to the bottom right of the header no matter what I do.  They usually just end up in the center, and I tried to float them but that definitely didn't work.  What's a good way to go about styling buttons in CSS?

HTML:

    .clear {
 clear: both;
    }

    #container{
        margin: 0 auto;
        max-width: 1200px;
    }
    header {
        width: 94%;
        padding: 3%;
        background-color: #F3D22D;
    }
    header #title {
        font-size: 50px;
        color: #fff;
    }
    nav {
        width: 97%;
        background-color: #DDCFC5;
        padding: 0 1.5% 0 1.5%;
    }
    nav ul li {
        display: inline-block;
        padding: 15px 1.5% 15px 1.5% ;
    }
    nav ul li a {
        text-decoration: none;
        color: #ffffff;
        font-size: 1.2em;
    }
     nav ul li a:hover {
         color: #000000;
         text-decoration: none;
     }
     #content {
        float: left;
        padding: 3%;
        width: 64%;
    }
    aside {
        float: right;
        padding: 3%;
        width: 24%;
        background-color: #DDCFC5;
    }
    footer{
        width: 94%;
        padding: 3%;
        background-color: #F3D22D;
        border-top: 5px solid #DDCFC5;
        color: #fff;
        text-align: center;
    }
    @media all and (max-width : 768px) {
        header {
            text-align: center;
        }
        nav {
            text-align: center;
        }
        #content {
            width: 94%;
            padding: 3%;
        }
        #sidebar {
            width: 94%;
            padding: 3%;
            border-top: 3px solid #E64A19;
        }
    }
    @media all and (max-width : 330px) {
        nav ul li {
            display:block;
            width: 94%;
        }
    }

    button {
     background-color: #4CAF50;
     border: none;
     color: white;
     padding: 15px 32px;
     text-align: center;
     text-decoration: none;
     display: inline-block;
     font-size: 16px;
     margin: 4px 2px;
     cursor: pointer;
    }

    #usermenu {
     bottom: 0;
     left: 0;
    }

    <!DOCTYPE html>

  <title>Website</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link type="text/css? rel="stylesheet" href="reset.css" />
  <link type="text/css" rel="stylesheet" href="style.css" />

Website

     <button  type="button">Login</button>
     <button type="button">Sign Up</button>

Home

About

Contact

Built with HTML5 and CSS3

         More content here................

         Hello... blah blahblah

This is the sidebar

content goes here...

        Copyright &copy Gregory Soble 2017

Body:
By default the position of an element is static, so values for top, right, bottom, and left have no effect at all.  You need to give the element/elements another value for position to be able to "position" them.

.clear {
clear: both;
}

#container{
    margin: 0 auto;
    max-width: 1200px;
}
header {
    position: relative;
    width: 94%;
    padding: 3%;
    background-color: #F3D22D;
}
header #title {
    font-size: 50px;
    color: #fff;
}
nav {
    width: 97%;
    background-color: #DDCFC5;
    padding: 0 1.5% 0 1.5%;
}
nav ul li {
    display: inline-block;
    padding: 15px 1.5% 15px 1.5% ;
}
nav ul li a {
    text-decoration: none;
    color: #ffffff;
    font-size: 1.2em;
}
 nav ul li a:hover {
     color: #000000;
     text-decoration: none;
 }
 #content {
    float: left;
    padding: 3%;
    width: 64%;
}
aside {
    float: right;
    padding: 3%;
    width: 24%;
    background-color: #DDCFC5;
}
footer{
    width: 94%;
    padding: 3%;
    background-color: #F3D22D;
    border-top: 5px solid #DDCFC5;
    color: #fff;
    text-align: center;
}
@media all and (max-width : 768px) {
    header {
        text-align: center;
    }
    nav {
        text-align: center;
    }
    #content {
        width: 94%;
        padding: 3%;
    }
    #sidebar {
        width: 94%;
        padding: 3%;
        border-top: 3px solid #E64A19;
    }
}
@media all and (max-width : 330px) {
    nav ul li {
        display:block;
        width: 94%;
    }
}

button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

#usermenu {
    position: absolute;
    bottom: 0;
    right: 0;
}

    <div id="container">
        <!-- header -->
        <header id="header">
            <h1 id="title">Website</h1>
            <div id="usermenu">
                <button  type="button">Login</button>
                <button type="button">Sign Up</button>
            </div>
        </header>
        <!-- navigation -->
        <nav id="menu" class="clearfix">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>

            <!-- main content area -->

            <section id="content">
                <h2>Built with HTML5 and CSS3</h2>
                <p>
                    More content here................
                    <br>
                    Hello... blah blahblah
                </p>
            </section>

            <!-- sidebar -->
            <aside id="sidebar">
                <h3>This is the sidebar</h3>
                <p>content goes here...</p>
            </aside>
            <div class="clear"></div>
            <!-- footer -->
            <footer id="footer" class="clearfix">
                Copyright &copy Gregory Soble 2017
            </footer>
        </div>


问:
Selecting Parent's Child in jQuery
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

```<code>$("nav ul li > ul").parent().append('<span class="arrow">↓</span>');
</code>```

HTML:

```<code><li><a href="#">The Events</a>
  <ul>
    <li><a href="#">Schedule</a></li>
    <li><a href="#">Buy Tickets</a></li>
    <li><a href="#">Features</a></li>
  </ul>
</li>
</code>```

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.

答:
You can use .siblings(), like this:

```<code>$("nav ul li > ul").siblings("a").append('<span class="arrow">↓</span>');
</code>```

You can find a full list of traversal functions here.

Title: Selecting Parent's Child in jQuery

Body:
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

$("nav ul li > ul").parent().append('↓');

HTML:

The Events

Schedule

Buy Tickets

Features

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.

Body:
You can use .siblings(), like this:

$("nav ul li > ul").siblings("a").append('<span class="arrow">&darr;</span>');

You can find a full list of traversal functions here.


答:
I assume this question is being asked with the assumption that the data is in a given, particular, and consistent format (otherwise this formatting is pointless). Below is shown an implementation providing the desired results:

```<code>SELECT
  STUFF(
    (
      SELECT
        CASE WHEN (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 2 = 0) AND LEFT([value], 1) <> '(' AND RIGHT([value], 1) <> ')' THEN CONCAT(',', value)
        ELSE CONCAT(' ', value) END
      FROM
        STRING_SPLIT('245 289 252 722 265,420 (22,791) (23,482) (24,662)', ' ')
      FOR XML PATH('')
    ),
    1,
    1,
    ''
  ) AS [value]
</code>```

Input: 245 289 252 722 265,420 (22,791) (23,482) (24,662)

Output: 245,289 252,722 265,420 (22,791) (23,482) (24,662)

Compatibility level 130 must be set in order to use STRING_SPLIT

Title: How to replace space between a number with comma using SQL Server?

Body:
SELECT REPLACE('245 289 252 722 265,420 (22,791) (23,482) (24,662)', '^[0-9]', ',')

Raw Result      : 245 289 252 722 265,420 (22,791) (23,482) (24,662)

Need Result     : 245,289 252,722 265,420 (22,791) (23,482) (24,662)

Body:
I assume this question is being asked with the assumption that the data is in a given, particular, and consistent format (otherwise this formatting is pointless). Below is shown an implementation providing the desired results:

SELECT
  STUFF(
    (
      SELECT
        CASE WHEN (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 2 = 0) AND LEFT([value], 1) <> '(' AND RIGHT([value], 1) <> ')' THEN CONCAT(',', value)
        ELSE CONCAT(' ', value) END
      FROM
        STRING_SPLIT('245 289 252 722 265,420 (22,791) (23,482) (24,662)', ' ')
      FOR XML PATH('')
    ),
    1,
    1,
    ''
  ) AS [value]

Input: 245 289 252 722 265,420 (22,791) (23,482) (24,662)

Output: 245,289 252,722 265,420 (22,791) (23,482) (24,662)

Compatibility level 130 must be set in order to use STRING_SPLIT


答:
in python, you could open the file as a string, remove the first character, and wirte the file again.</p>

```<code>myfile = open("yourfilehere", "r")
mylist = myfile.readlines()
mytext = ""
for items in mylist:
    mytext = mytext + items +"\n"
myfile.close()
mytext = mytext[1:]
myfile = open("yourfilehere", "w")
myfile.write(mytext)
</code>```

Title: Delete first character from a text file

Body: I have a text file in which the first character - I want to delete, but I am not getting either its a CR or LF character, how Can I delete the file character from the entire file.

Body:
in python, you could open the file as a string, remove the first character, and wirte the file again.

myfile = open("yourfilehere", "r")
mylist = myfile.readlines()
mytext = ""
for items in mylist:
    mytext = mytext + items +"\n"
myfile.close()
mytext = mytext[1:]
myfile = open("yourfilehere", "w")
myfile.write(mytext)


问:
Return value instead of a promise [to stop nested deferred promise]
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

```<code>let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }
</code>```

Child 1

```<code>$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }
</code>```

Child 2

```<code>let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}
</code>```

Level 3

```<code>checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })
</code>```

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

```<code>$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }
</code>```

答:
You can use for it async/await construction. And use Babel for support old browsers.

Async

Await

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
  console.log('done');
}

f1();```

Body:
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }

Child 1

$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }

Child 2

let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}

Level 3

checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }


问:
Pandas: Matrix Multiplication
I am attempting to find the best method for matrix multiplication using pandas.  Suppose I want to do a simple exercise: xyx' ...[1x5][5x5][5x1]'.

```<code>in:

ydates = pd.date_range('20170101',periods=5)
y = pd.DataFrame(np.identity(5),index=['f','o','b','a','r'],columns=['f','o','b','a','r'])
xdata = list(range(1,6))
x = pd.DataFrame(xdata,index=['f','o','b','a','r'])
x.loc['o'] = np.nan
mm = x.T.dot(y)*x.T

out:

        f   o   b   a   r
    0 NaN NaN NaN NaN NaN
</code>```

I would expect to get:

```<code>     0
f  1.0
o  NaN
b  3.0
a  4.0
r  5.0
</code>```

My questions are:

1) How do I align these? Is there a better way than doing the double transpose?

2) Is there a way to account for nans?

2) Is there a more efficient way to do matrix algebra using python/pandas?

答:
numpyhas several functions that handle matrix products - np.dot, np.einsum and np.matmul (and the @ operator).  * is defined as element wise multiplication (except for np.matrix class).  All are optimized for speed.  But they also propagate nan.

Using numpy arrays instead of pandas:

```<code>In [314]: y = np.eye(5)
In [316]: y
Out[316]:
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])
</code>```

To do transpose on x we need to make it 2d; and to assign nan it has to be float.

```<code>In [320]: x = np.arange(1,6).astype(float).reshape(1,5)
In [321]: x[0,1]=np.nan
In [322]: x
Out[322]: array([[  1.,  nan,   3.,   4.,   5.]])
In [323]: x.T       # column vector
Out[323]:
array([[  1.],
       [ nan],
       [  3.],
       [  4.],
       [  5.]])
In [324]: np.dot(y, x.T)
Out[324]:
array([[ nan],
       [ nan],
       [ nan],
       [ nan],
       [ nan]])
</code>```

Why this dot result?  It multiplies each row of y by the column of x.T, and sums the values.  Because of the nan one of those products for each row of y is 1*nan or 0*nan; any product or sum involving nan produces nan, to the result is all nan.

I suspect you were hoping that 0*nan == 0.  Like:

```<code>In [329]: x[0,1]=100
In [330]: np.dot(y, x.T)
Out[330]:
array([[   1.],
       [ 100.],
       [   3.],
       [   4.],
       [   5.]])
</code>```

There are some numpy functions that skip nan. np.dot isn't one of them.

```<code>In [333]: x[0,1]=np.nan
In [336]: y*x
Out[336]:
array([[  1.,  nan,   0.,   0.,   0.],
       [  0.,  nan,   0.,   0.,   0.],
       [  0.,  nan,   3.,   0.,   0.],
       [  0.,  nan,   0.,   4.,   0.],
       [  0.,  nan,   0.,   0.,   5.]])
In [339]: np.nansum(y*x, axis=1, keepdims=True)
Out[339]:
array([[ 1.],
       [ 0.],
       [ 3.],
       [ 4.],
       [ 5.]])
</code>```

This sort of works.  It skipped the nan when summing across rows; but the 2nd value is 0, not nan.

The np.nan... functions work by temporarily replacing the nan with something innocuous like 0 or 1.  I could do that in your case with:

```<code>In [369]: x
Out[369]: array([[  1.,  nan,   3.,   4.,   5.]])
In [370]: x1, mask = np.lib.nanfunctions._replace_nan(x.T,1)
In [371]: x1
Out[371]:
array([[ 1.],
       [ 1.],
       [ 3.],
       [ 4.],
       [ 5.]])
In [372]: mask
Out[372]:
array([[False],
       [ True],
       [False],
       [False],
       [False]], dtype=bool)
In [373]: x2 = np.dot(y, x1)
In [374]: x2[mask] = np.nan
In [375]: x2
Out[375]:
array([[  1.],
       [ nan],
       [  3.],
       [  4.],
       [  5.]])
</code>```

Title: Pandas: Matrix Multiplication

Body:
I am attempting to find the best method for matrix multiplication using pandas.  Suppose I want to do a simple exercise: xyx' ...[1x5][5x5][5x1]'.

in:

ydates = pd.date_range('20170101',periods=5)
y = pd.DataFrame(np.identity(5),index=['f','o','b','a','r'],columns=['f','o','b','a','r'])
xdata = list(range(1,6))
x = pd.DataFrame(xdata,index=['f','o','b','a','r'])
x.loc['o'] = np.nan
mm = x.T.dot(y)*x.T

out:

        f   o   b   a   r
    0 NaN NaN NaN NaN NaN

I would expect to get:

     0
f  1.0
o  NaN
b  3.0
a  4.0
r  5.0

My questions are:

1) How do I align these? Is there a better way than doing the double transpose?

2) Is there a way to account for nans?

2) Is there a more efficient way to do matrix algebra using python/pandas?

Body:
numpyhas several functions that handle matrix products - np.dot, np.einsum and np.matmul (and the @ operator).  * is defined as element wise multiplication (except for np.matrix class).  All are optimized for speed.  But they also propagate nan.

Using numpy arrays instead of pandas:

In [314]: y = np.eye(5)
In [316]: y
Out[316]:
array([[ 1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.]])

To do transpose on x we need to make it 2d; and to assign nan it has to be float.

In [320]: x = np.arange(1,6).astype(float).reshape(1,5)
In [321]: x[0,1]=np.nan
In [322]: x
Out[322]: array([[  1.,  nan,   3.,   4.,   5.]])
In [323]: x.T       # column vector
Out[323]:
array([[  1.],
       [ nan],
       [  3.],
       [  4.],
       [  5.]])
In [324]: np.dot(y, x.T)
Out[324]:
array([[ nan],
       [ nan],
       [ nan],
       [ nan],
       [ nan]])

Why this dot result?  It multiplies each row of y by the column of x.T, and sums the values.  Because of the nan one of those products for each row of y is 1*nan or 0*nan; any product or sum involving nan produces nan, to the result is all nan.

I suspect you were hoping that 0*nan == 0.  Like:

In [329]: x[0,1]=100
In [330]: np.dot(y, x.T)
Out[330]:
array([[   1.],
       [ 100.],
       [   3.],
       [   4.],
       [   5.]])

There are some numpy functions that skip nan. np.dot isn't one of them.

In [333]: x[0,1]=np.nan
In [336]: y*x
Out[336]:
array([[  1.,  nan,   0.,   0.,   0.],
       [  0.,  nan,   0.,   0.,   0.],
       [  0.,  nan,   3.,   0.,   0.],
       [  0.,  nan,   0.,   4.,   0.],
       [  0.,  nan,   0.,   0.,   5.]])
In [339]: np.nansum(y*x, axis=1, keepdims=True)
Out[339]:
array([[ 1.],
       [ 0.],
       [ 3.],
       [ 4.],
       [ 5.]])

This sort of works.  It skipped the nan when summing across rows; but the 2nd value is 0, not nan.

The np.nan... functions work by temporarily replacing the nan with something innocuous like 0 or 1.  I could do that in your case with:

In [369]: x
Out[369]: array([[  1.,  nan,   3.,   4.,   5.]])
In [370]: x1, mask = np.lib.nanfunctions._replace_nan(x.T,1)
In [371]: x1
Out[371]:
array([[ 1.],
       [ 1.],
       [ 3.],
       [ 4.],
       [ 5.]])
In [372]: mask
Out[372]:
array([[False],
       [ True],
       [False],
       [False],
       [False]], dtype=bool)
In [373]: x2 = np.dot(y, x1)
In [374]: x2[mask] = np.nan
In [375]: x2
Out[375]:
array([[  1.],
       [ nan],
       [  3.],
       [  4.],
       [  5.]])


问:
AngularDart Dialog service
I need to open a dialog (modal) in a component in an ngFor loop. I'm pretty sure repeating the modal inside my component is not the answer.

I'm looking for a way to have a Dialog Service in AngulatDart, in Angular2 (TS) I would do something like :

```<code>@Injectable()
export class MyDialogService {
  constructor(private dialog: MdDialog) {
  }

  public openDialog() {
    let dialogRef: MdDialogRef<MyDialogComponent>;
    dialogRef = this.dialog.open(MyDialogComponent);
    return dialogRef.afterClosed();
  }
}
</code>```

I didn't find a way to do the same in AngularDart

答: As Gunter mentioned, there is no provided "DialogService" in the set of AngularDart components. You could file a feature request, but I imagine creating such a service would be really easy - you could add a <material-dialog> in your root level component and expose your root component as an injectable service to show or hide it.

Title: AngularDart Dialog service

Body:
I need to open a dialog (modal) in a component in an ngFor loop. I'm pretty sure repeating the modal inside my component is not the answer.

I'm looking for a way to have a Dialog Service in AngulatDart, in Angular2 (TS) I would do something like :

@Injectable()
export class MyDialogService {
  constructor(private dialog: MdDialog) {
  }

  public openDialog() {
    let dialogRef: MdDialogRef<MyDialogComponent>;
    dialogRef = this.dialog.open(MyDialogComponent);
    return dialogRef.afterClosed();
  }
}

I didn't find a way to do the same in AngularDart


问:
VS 2017 Team Explorer GIT "Push Branch" Grayed out
VS 2017 Team Explorer GIT "Push Branch" is Grayed out for me. I create a new local branch from a remote branch with no tracking and then I try to create a remote branch with the same name as the local branch by clicking on "Push Branch". Why would this option be grayed out for me?</p>

答:
The direct way to push a new created local branch to VSTS git repo by VS is clicking push branch button directly on local branch (don’t need to create the same branch in remote manually).

Detail steps as: VS -> Team explorer -> Branches -> right click the local branch -> Push branch -> then the local branch is pushed to remote.

Since you have already created the same branch on remote, you can fetch first and then push:
Team explorer ->Sync -> Fetch -> push.

when you clone the remote repo (no matter on VSTS or bitbucket) again, and siwtch to the new created branch, the branch willexist in remotes/origin, so you can push directly.


问:
MySQL AUTO_INCREMENT does not ROLLBACK
I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this? </p>

答:
It can't work that way. Consider:

program one, you open a transaction and insert into a table FOO which has an autoinc primary key (arbitrarily, we say it gets 557 for its key value).

Program two starts, it opens a transaction and inserts into table FOO getting 558.

Program two inserts into table BAR which has a column which is a foreign key to FOO. So now the 558 is located in both FOO and BAR.

Program two now commits.

Program three starts and generates a report from table FOO. The 558 record is printed.

After that, program one rolls back.

How does the database reclaim the 557 value? Does it go into FOO and decrement all the other primary keys greater than 557? How does it fix BAR? How does it erase the 558 printed on the report program three output?

Oracle's sequence numbers are also independent of transactions for the same reason.

If you can solve this problem in constant time, I'm sure you can make a lot of money in the database field.

Now, if you have a requirement that your auto increment field never have gaps (for auditing purposes, say). Then you cannot rollback your transactions. Instead you need to have a status flag on your records. On first insert, the record's status is "Incomplete" then you start the transaction, do your work and update the status to "compete" (or whatever you need). Then when you commit, the record is live. If the transaction rollsback, the incomplete record is still there for auditing. This will cause you many other headaches but is one way to deal with audit trails.

OwnerDisplayName: Gian Paulo

Title: MySQL AUTO_INCREMENT does not ROLLBACK


问:
Swift: Unknown error - Unexpectedly found nil while unwrapping an Optional value
I know this is a common error people post here but I can't find a post that matches to what I'm doing even if its the same fundamentally. I'm new to Swift and just trying to find my way, thank you.

The first time I open my app, a blog reader app that reads from a MYSQL database, it works as intended, I can follow the blogs that I chose and unfollow. When I follow a blog/cell it saves to User Defaults using KeyArchiver but when I double tap the home button to clear the app from memory and reopen the app, it crashes.

Something wrong is going on in my loadUserDefaults because I set up breakpoints and it crashes at this line self.followedIdentifiers = Set(UserDefaults.standard.stringArray(forKey: "followedID")!)

I know I have an optional but why is it crashing/ coming back nil if I saved it with saveUserDefaults. Is it not saving? or am I not loading it correctly?

The error is this

fatal error: unexpectedly found nil while unwrapping an Optional value

Code: This is MainController.swift

```<code>var mainArray = [Blog]()
var followedArray = [Blog]()
var filteredArray = [Blog]()
var followedIdentifiers = Set<String>()

override func viewDidLoad() {
    super.viewDidLoad()

    // Receiving Data from Server
    retrieveDataFromServer()

    // NSCoding - Unarchiving Data (followedID)
    loadUserDefaults()
}

// NSCoding: Archiving UserDefaults
func saveUserDefaults() {

    // Saving to UserDefaults
    let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.followedIdentifiers)
    UserDefaults.standard.setValue(encodedData, forKey: "followedID")
    UserDefaults.standard.synchronize()
}

// NSCoding: Unarchiving UserDefaults
func loadUserDefaults() { // --- Crash is Here ---

    // Unarchiving Data
    if let data = UserDefaults.standard.data(forKey: "followedID"), let myFollowedList = NSKeyedUnarchiver.unarchiveObject(with: data) as? Set<String> {

        self.followedIdentifiers = myFollowedList
        self.followedIdentifiers = Set(UserDefaults.standard.stringArray(forKey: "followedID")!) // CRASH

    } else {
        print("Error/ Empty: (Loading UserDefaults (followedID))")
    }
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if identifiers match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}
</code>```

This is Blog.swift which handles all the blogs objects and NSCoding

```<code>class Blog: NSObject, NSCoding {

var blogName: String
var blogStatus1: String
var blogStatus2: String
var blogURL: String
var blogID: String
var blogType: String
var blogDate: String
var blogPop: String

private init (name: String,status1: String,status2: String,url: String,id: String,type: String,date: String,pop: String) {
    blogName = name
    blogStatus1 = status1
    blogStatus2 = status2
    blogURL = url
    blogID = id
    blogType = type
    blogDate = date
    blogPop = pop
    super.init()
}

convenience init?(jsonObject: [String:Any]) {

    guard let bID = jsonObject["id"] as? String,
        let bName = jsonObject["blogName"] as? String,
        let bStatus1 = jsonObject["blogStatus1"] as? String,
        let bStatus2 = jsonObject["blogStatus2"] as? String,
        let bURL = jsonObject["blogURL"] as? String,
        let bType = jsonObject["blogType"] as? String,
        let bDate = jsonObject["blogDate"] as? String,
        let bPop = jsonObject["blogPop"] as? String

        else {
            print("Error: (Creating Blog Object)")
            return nil
    }

    self.init(name: bName, status1: bStatus1, status2: bStatus2, url: bURL, id: bID, type: bType, date: bDate, pop: bPop)

}

convenience required init?(coder aDecoder: NSCoder) {
    guard let blogName = aDecoder.decodeObject(forKey: "blogName") as? String,
        let blogStatus1 = aDecoder.decodeObject(forKey: "blogStatus1") as? String,
        let blogStatus2 = aDecoder.decodeObject(forKey: "blogStatus2") as? String,
        let blogURL = aDecoder.decodeObject(forKey: "blogURL") as? String,
        let blogID = aDecoder.decodeObject(forKey: "blogID") as? String,
        let blogType = aDecoder.decodeObject(forKey: "blogType") as? String,
        let blogDate = aDecoder.decodeObject(forKey: "blogDate") as? String,
        let blogPop = aDecoder.decodeObject(forKey: "blogPop") as? String else {
            print("Error: (Creating Blog Object)")
            return nil
    }
    self.init(name: blogName, status1: blogStatus1, status2: blogStatus2, url: blogURL, id: blogID, type: blogType, date: blogDate, pop: blogPop)
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(blogName, forKey: "blogName")
    aCoder.encode(blogStatus1, forKey: "blogStatus1")
    aCoder.encode(blogStatus2, forKey: "blogStatus2")
    aCoder.encode(blogURL, forKey: "blogURL")
    aCoder.encode(blogID, forKey: "blogID")
    aCoder.encode(blogType, forKey: "blogType")
    aCoder.encode(blogDate, forKey: "blogDate")
    aCoder.encode(blogPop, forKey: "blogPop")
 }
}
</code>```

答:
I used File Manager to save my archived array and it was the best choice, so easy and simple. Using Swift 3. Credit to @GuyKogus, @Paulw11 & @MartinR

Used to save my object

```<code>NSKeyedArchiver.archiveRootObject(myObject, toFile: filePath)
</code>```

Used to load my object

```<code>if let myFollowedList = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Set<String> {

    myObject = myFollowedList
}
</code>```

Body:
I know this is a common error people post here but I can't find a post that matches to what I'm doing even if its the same fundamentally. I'm new to Swift and just trying to find my way, thank you.

The first time I open my app, a blog reader app that reads from a MYSQL database, it works as intended, I can follow the blogs that I chose and unfollow. When I follow a blog/cell it saves to User Defaults using KeyArchiver but when I double tap the home button to clear the app from memory and reopen the app, it crashes.

Something wrong is going on in my loadUserDefaults because I set up breakpoints and it crashes at this line self.followedIdentifiers = Set(UserDefaults.standard.stringArray(forKey: "followedID")!)

I know I have an optional but why is it crashing/ coming back nil if I saved it with saveUserDefaults. Is it not saving? or am I not loading it correctly?

The error is this

fatal error: unexpectedly found nil while unwrapping an Optional value

Code: This is MainController.swift

var mainArray = [Blog]()
var followedArray = [Blog]()
var filteredArray = [Blog]()
var followedIdentifiers = Set<String>()

override func viewDidLoad() {
    super.viewDidLoad()

    // Receiving Data from Server
    retrieveDataFromServer()

    // NSCoding - Unarchiving Data (followedID)
    loadUserDefaults()
}

// NSCoding: Archiving UserDefaults
func saveUserDefaults() {

    // Saving to UserDefaults
    let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.followedIdentifiers)
    UserDefaults.standard.setValue(encodedData, forKey: "followedID")
    UserDefaults.standard.synchronize()
}

// NSCoding: Unarchiving UserDefaults
func loadUserDefaults() { // --- Crash is Here ---

    // Unarchiving Data
    if let data = UserDefaults.standard.data(forKey: "followedID"), let myFollowedList = NSKeyedUnarchiver.unarchiveObject(with: data) as? Set<String> {

        self.followedIdentifiers = myFollowedList
        self.followedIdentifiers = Set(UserDefaults.standard.stringArray(forKey: "followedID")!) // CRASH

    } else {
        print("Error/ Empty: (Loading UserDefaults (followedID))")
    }
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if identifiers match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}

This is Blog.swift which handles all the blogs objects and NSCoding

class Blog: NSObject, NSCoding {

var blogName: String
var blogStatus1: String
var blogStatus2: String
var blogURL: String
var blogID: String
var blogType: String
var blogDate: String
var blogPop: String

private init (name: String,status1: String,status2: String,url: String,id: String,type: String,date: String,pop: String) {
    blogName = name
    blogStatus1 = status1
    blogStatus2 = status2
    blogURL = url
    blogID = id
    blogType = type
    blogDate = date
    blogPop = pop
    super.init()
}

convenience init?(jsonObject: [String:Any]) {

    guard let bID = jsonObject["id"] as? String,
        let bName = jsonObject["blogName"] as? String,
        let bStatus1 = jsonObject["blogStatus1"] as? String,
        let bStatus2 = jsonObject["blogStatus2"] as? String,
        let bURL = jsonObject["blogURL"] as? String,
        let bType = jsonObject["blogType"] as? String,
        let bDate = jsonObject["blogDate"] as? String,
        let bPop = jsonObject["blogPop"] as? String

        else {
            print("Error: (Creating Blog Object)")
            return nil
    }

    self.init(name: bName, status1: bStatus1, status2: bStatus2, url: bURL, id: bID, type: bType, date: bDate, pop: bPop)

}

convenience required init?(coder aDecoder: NSCoder) {
    guard let blogName = aDecoder.decodeObject(forKey: "blogName") as? String,
        let blogStatus1 = aDecoder.decodeObject(forKey: "blogStatus1") as? String,
        let blogStatus2 = aDecoder.decodeObject(forKey: "blogStatus2") as? String,
        let blogURL = aDecoder.decodeObject(forKey: "blogURL") as? String,
        let blogID = aDecoder.decodeObject(forKey: "blogID") as? String,
        let blogType = aDecoder.decodeObject(forKey: "blogType") as? String,
        let blogDate = aDecoder.decodeObject(forKey: "blogDate") as? String,
        let blogPop = aDecoder.decodeObject(forKey: "blogPop") as? String else {
            print("Error: (Creating Blog Object)")
            return nil
    }
    self.init(name: blogName, status1: blogStatus1, status2: blogStatus2, url: blogURL, id: blogID, type: blogType, date: blogDate, pop: blogPop)
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(blogName, forKey: "blogName")
    aCoder.encode(blogStatus1, forKey: "blogStatus1")
    aCoder.encode(blogStatus2, forKey: "blogStatus2")
    aCoder.encode(blogURL, forKey: "blogURL")
    aCoder.encode(blogID, forKey: "blogID")
    aCoder.encode(blogType, forKey: "blogType")
    aCoder.encode(blogDate, forKey: "blogDate")
    aCoder.encode(blogPop, forKey: "blogPop")
 }
}

Body:
I used File Manager to save my archived array and it was the best choice, so easy and simple. Using Swift 3. Credit to @GuyKogus, @Paulw11 & @MartinR

Used to save my object

NSKeyedArchiver.archiveRootObject(myObject, toFile: filePath)

Used to load my object

if let myFollowedList = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Set<String> {

    myObject = myFollowedList
}