问:
Looping through a column to move cells with font size 10 down one row
I have section title cells set at 10 pt font while all other data is set at 9 point font in column A.  I am trying to write a vba macro to loop through column A to move each title cell down one row(because the csv leaves a blank cell below them) then move on to the next title cell in the column.  Here is my attempt but I'm not sure what I'm doing wrong here.</p>

```<code>Sub FontSpacing()
    Dim Fnt As Range

  For Each Fnt In Range("A8:A5000")
      If Fnt.Font.Size = "10" Then
       ActiveCell.Cut Destination:=ActiveCell.Offset(",1")
  End If
Next
</code>```

答:
Try this

```<code>Sub FontSpacing()
    Dim r As Range

    For Each r In ThisWorkbook.Worksheets("Sheet1").Range("A8:A5000")
        If r.Font.Size = 10 Then
            r.Offset(1,0).Value = r.Value
            r.Value = vbNullString
        End If
    Next r
End Sub
</code>```

The issues:

Offset(",1") shouldn't have the speech marks. I.e. it should be Offset(0,1). In fact, if you want to paste to the row below, then it should be Offset(1,0).

Avoid using ActiveCell. It's not the cell that is looping through your range, it's just the cell that was active on the worksheet when you ran the sub.

Fnt is a bad name for a range, it's probably the reason you got confused. When declaring (dimensioning) a range, try to give it a name that makes it clear you're working with a range.

Extra:

Fully qualify your range reference to avoid an implicit reference to the ActiveSheet e.g. ThisWorkbook.Worksheets("Sheet1").Range("A1").

Avoid cutting an pasting by setting the Value directly

Your indentation is out, which makes it look like a complete Sub, but it's missing the End Sub.

Body:
I have section title cells set at 10 pt font while all other data is set at 9 point font in column A.  I am trying to write a vba macro to loop through column A to move each title cell down one row(because the csv leaves a blank cell below them) then move on to the next title cell in the column.  Here is my attempt but I'm not sure what I'm doing wrong here.

Sub FontSpacing()
    Dim Fnt As Range

  For Each Fnt In Range("A8:A5000")
      If Fnt.Font.Size = "10" Then
       ActiveCell.Cut Destination:=ActiveCell.Offset(",1")
  End If
Next

Body:
Try this

Sub FontSpacing()
    Dim r As Range

    For Each r In ThisWorkbook.Worksheets("Sheet1").Range("A8:A5000")
        If r.Font.Size = 10 Then
            r.Offset(1,0).Value = r.Value
            r.Value = vbNullString
        End If
    Next r
End Sub

The issues:

Offset(",1") shouldn't have the speech marks. I.e. it should be Offset(0,1). In fact, if you want to paste to the row below, then it should be Offset(1,0).

Avoid using ActiveCell. It's not the cell that is looping through your range, it's just the cell that was active on the worksheet when you ran the sub.

Fnt is a bad name for a range, it's probably the reason you got confused. When declaring (dimensioning) a range, try to give it a name that makes it clear you're working with a range.

Extra:

Fully qualify your range reference to avoid an implicit reference to the ActiveSheet e.g. ThisWorkbook.Worksheets("Sheet1").Range("A1").

Avoid cutting an pasting by setting the Value directly

Your indentation is out, which makes it look like a complete Sub, but it's missing the End Sub.


来源: stackexchange

问:
Condition variable WinAPI does't work. Why?
I want to synchronize threads, that generates automatically. I write such code. This code periodically write names of every thread in such sequence they are generated.

But when I run my code, sometimes I have a nice result and sometimes I have something such a bug: all are hang (sleep with clearly black screen). It happens accidentally.

With debugging I understand that sometimes child thread doesn't want to wake up. Who can tell: why? And how can I fix that?

I use Microsoft Visual Studio 2010 SP1 Professional on Windows 10 x64.

And my code:

main.cpp

```<code>#include "ThreadManager.h"
#include "ThreadFuncs.h"

int main() {
    ThreadManager mng(2.0, 1.3);
    mng.runAll();

    Sleep(100000);

    return 0;
}
</code>```

ThreadFuncs.cpp

```<code>#include <iostream>
#include <string>

#include "Sync.h"
#include "ThreadManager.h"

#include "ThreadFuncs.h"

DWORD WINAPI threadPrinter(LPVOID ptr)
{
    ThreadManager* manager = reinterpret_cast<ThreadManager*>(ptr);
    if (!manager)
    {
        return 1;
    }

    CRITICAL_SECTION cs;
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);

    while (!manager->isStopPrinting)
    {
        EnterCriticalSection(&manager->workWithFlags);

        for (auto it = manager->flags.begin(); it != manager->flags.end(); ++it)
        {
            (*it)->operation = OPERATION_START_WRITING_NAME;
            WakeConditionVariable(&(*it)->canWork);

            SleepConditionVariableCS(&(*it)->isEndWork, &cs, INFINITE);
        }

        LeaveCriticalSection(&manager->workWithFlags);

        Sleep(manager->showInterval * 1000);
    }

    LeaveCriticalSection(&cs);
    DeleteCriticalSection(&cs);

    return 0;
}

DWORD WINAPI threadGenerator(LPVOID ptr)
{
    ThreadManager* manager = reinterpret_cast<ThreadManager*>(ptr);
    if (!manager)
    {
        return 1;
    }

    while (!manager->isStopGeneration)
    {
        manager->generateNewThread();

        Sleep(manager->createNewThreadInterval * 1000);
    }

    return 0;
}

DWORD WINAPI threadChild(LPVOID ptr)
{
    Sync* s = reinterpret_cast<Sync*> (ptr);
    if (s == NULL)
    {
        return 1;
    }

    std::string name = "Th_" + std::to_string(static_cast<long long>(s->index));

    CRITICAL_SECTION cs;
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);

    while (true)
    {
        SleepConditionVariableCS(&s->canWork, &cs, INFINITE);

        if (s->operation == OPERATION_EXIT_THREAD)
        {
            break;
        }

        if (s->operation == OPERATION_START_WRITING_NAME)
        {
            std::cout << name << " ";
            WakeConditionVariable(&s->isEndWork);
            continue;
        }

        WakeConditionVariable(&s->isEndWork);
    }

    LeaveCriticalSection(&cs);
    DeleteCriticalSection(&cs);

    return 0;
}
</code>```

ThreadManager.h

```<code>#pragma once

#include <windows.h>
#include <deque>
#include "Sync.h"
#include "ThreadFuncs.h"

class ThreadManager
{
    std::deque <Sync *> flags;
    CRITICAL_SECTION workWithFlags;

    friend DWORD WINAPI threadGenerator(LPVOID);
    friend DWORD WINAPI threadPrinter(LPVOID);

    HANDLE printerThread;
    HANDLE generatorThread;

    const double showInterval;
    const double createNewThreadInterval;
    bool isStopGeneration;
    bool isStopPrinting;

public:
    ThreadManager(const double& showInterval, const double& createNewThreadInterval);
    ~ThreadManager();

    void generateNewThread();
    bool removeThread();            //kill random thread
    bool removeThread(int index);

    void runAll();
    void stopAll();

    int getNumOfThreads() const;
};
</code>```

ThreadManager.cpp

```<code>#include "ThreadManager.h"

ThreadManager::ThreadManager(const double& showInterval, const double& createNewThreadInterval) :
    showInterval(showInterval), createNewThreadInterval(createNewThreadInterval), isStopGeneration(true), isStopPrinting(true)
{

    InitializeCriticalSection(&workWithFlags);

    printerThread = NULL;
    generatorThread = NULL;

}

int ThreadManager::getNumOfThreads() const
{
    return flags.size();
}

void ThreadManager::runAll()
{
    //run generation
    isStopGeneration = false;

    if (generatorThread != NULL)
    {
        return;
    }

    generatorThread = CreateThread(NULL, 0, threadGenerator, this, /*run immediately*/ 0, NULL);
    if (generatorThread == NULL)
    {
        //Stream::log("Error creating generation thread");
        isStopGeneration = true;
    }

    //run printing
    isStopPrinting = false;

    if (printerThread != NULL)
    {
        return;
    }

    printerThread = CreateThread(NULL, 0, threadPrinter, this, /*run immediately*/ 0, NULL);
    if (printerThread == NULL)
    {
        //Stream::log("Error creating printer thread");
        isStopPrinting = true;
    }
}

void ThreadManager::stopAll()
{
    //stop generation
    if (!generatorThread)
    {
        return;
    }

    isStopGeneration = true;

    WaitForSingleObject(generatorThread, INFINITE);

    CloseHandle(generatorThread);

    generatorThread = NULL;

    //stop printing
    if (!printerThread)
    {
        return;
    }

    isStopPrinting = true;

    WaitForSingleObject(printerThread, INFINITE);

    CloseHandle(printerThread);

    printerThread = NULL;
}

ThreadManager::~ThreadManager()
{
    stopAll();

    while (!flags.empty())
    {
        removeThread(flags.size() - 1);
    }

    DeleteCriticalSection(&workWithFlags);
}

void ThreadManager::generateNewThread()
{
    static int newIndex = 0;
    Sync* s = new Sync();

    s->index = newIndex;
    newIndex++;

    s->threadHandle = CreateThread(NULL, 0, threadChild, s, /*run immediately*/ 0, NULL);
    if (s->threadHandle == NULL)
    {
        //Stream::log("Error creating new thread");
        delete s;
        return;
    }

    EnterCriticalSection(&workWithFlags);
    flags.push_back(s);
    LeaveCriticalSection(&workWithFlags);
}

bool ThreadManager::removeThread(int index)
{
    EnterCriticalSection(&workWithFlags);

    if (flags.size() <= index || index < 0)
    {
        LeaveCriticalSection(&workWithFlags);
        return false;
    }

    Sync* s = flags[index];
    flags.erase(flags.begin() + index);

    s->operation = OPERATION_EXIT_THREAD;
    WakeConditionVariable(&s->canWork);

    WaitForSingleObject(s->threadHandle, INFINITE);

    delete s;

    LeaveCriticalSection(&workWithFlags);

    return true;
}

bool ThreadManager::removeThread()
{
    EnterCriticalSection(&workWithFlags);
    int size = flags.size();
    LeaveCriticalSection(&workWithFlags);

    if (!size)
    {
        return false;
    }

    return removeThread(rand() % size);
}
</code>```

Sync.h

```<code>#pragma once

#include <windows.h>

#define OPERATION_EXIT_THREAD 1
#define OPERATION_START_WRITING_NAME 2

struct Sync
{
    CONDITION_VARIABLE canWork;
    CONDITION_VARIABLE isEndWork;
    HANDLE threadHandle;        //handle to thread
    int operation;              //operation type: 1 - exit, 2 - start writing name
    int index;                  //thread index

    Sync()
    {
        InitializeConditionVariable(&canWork);
        InitializeConditionVariable(&isEndWork);
        threadHandle = NULL;
        operation = 0;
        index = -1;
    }

    ~Sync()
    {
        if (threadHandle)
        {
            CloseHandle(threadHandle);
        }
    }
};
</code>```

Updated:

Stack trace (that I understand that):

答:
Your threadPrinter() and threadChild() functions are not syncing threads correctly.  You are creating a new local CRITICAL_SECTION that is useless because other threads have no access to it, so it is not actually locking access to anything.  You are passing that local CRITICAL_SECTION to SleepConditionVariableCS() when you should be passing manager->workWithFlags instead.  But doing so introduces a new logic hole, because once a thread unlocks workWithFlags to wait on a condition variable, other threads are free to modify the contents of flags, which you are not checking for when the waiting thread re-acquires the workWithFlags lock when the condition variable is signaled.

Based on what you are attempting to do, you probably shouldn't be using condition variables at all.  A condition variable is meant to be used to unlock an acquired lock (either a Critical Section or a Slim Reader/Writer lock) while waiting for the variable to be signaled, and then re-acquire that same lock again once signaled.  That is not what you need in your code.  Using signalable events would make more sense.  Look at CreateEvent(), SetEvent()/ResetEvent(), and WaitForSingleObject().  Signal an event to start some work, and signal another event when that work is finished.  You don't need to use condition variables for that.

ContentLicense: CC BY-SA 3.0

Body:
I want to synchronize threads, that generates automatically. I write such code. This code periodically write names of every thread in such sequence they are generated.

But when I run my code, sometimes I have a nice result and sometimes I have something such a bug: all are hang (sleep with clearly black screen). It happens accidentally.

With debugging I understand that sometimes child thread doesn't want to wake up. Who can tell: why? And how can I fix that?

I use Microsoft Visual Studio 2010 SP1 Professional on Windows 10 x64.

And my code:

main.cpp

#include "ThreadManager.h"
#include "ThreadFuncs.h"

int main() {
    ThreadManager mng(2.0, 1.3);
    mng.runAll();

    Sleep(100000);

    return 0;
}

ThreadFuncs.cpp

#include <iostream>
#include <string>

#include "Sync.h"
#include "ThreadManager.h"

#include "ThreadFuncs.h"

DWORD WINAPI threadPrinter(LPVOID ptr)
{
    ThreadManager* manager = reinterpret_cast<ThreadManager*>(ptr);
    if (!manager)
    {
        return 1;
    }

    CRITICAL_SECTION cs;
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);

    while (!manager->isStopPrinting)
    {
        EnterCriticalSection(&manager->workWithFlags);

        for (auto it = manager->flags.begin(); it != manager->flags.end(); ++it)
        {
            (*it)->operation = OPERATION_START_WRITING_NAME;
            WakeConditionVariable(&(*it)->canWork);

            SleepConditionVariableCS(&(*it)->isEndWork, &cs, INFINITE);
        }

        LeaveCriticalSection(&manager->workWithFlags);

        Sleep(manager->showInterval * 1000);
    }

    LeaveCriticalSection(&cs);
    DeleteCriticalSection(&cs);

    return 0;
}

DWORD WINAPI threadGenerator(LPVOID ptr)
{
    ThreadManager* manager = reinterpret_cast<ThreadManager*>(ptr);
    if (!manager)
    {
        return 1;
    }

    while (!manager->isStopGeneration)
    {
        manager->generateNewThread();

        Sleep(manager->createNewThreadInterval * 1000);
    }

    return 0;
}

DWORD WINAPI threadChild(LPVOID ptr)
{
    Sync* s = reinterpret_cast<Sync*> (ptr);
    if (s == NULL)
    {
        return 1;
    }

    std::string name = "Th_" + std::to_string(static_cast<long long>(s->index));

    CRITICAL_SECTION cs;
    InitializeCriticalSection(&cs);
    EnterCriticalSection(&cs);

    while (true)
    {
        SleepConditionVariableCS(&s->canWork, &cs, INFINITE);

        if (s->operation == OPERATION_EXIT_THREAD)
        {
            break;
        }

        if (s->operation == OPERATION_START_WRITING_NAME)
        {
            std::cout << name << " ";
            WakeConditionVariable(&s->isEndWork);
            continue;
        }

        WakeConditionVariable(&s->isEndWork);
    }

    LeaveCriticalSection(&cs);
    DeleteCriticalSection(&cs);

    return 0;
}

ThreadManager.h

#pragma once

#include <windows.h>
#include <deque>
#include "Sync.h"
#include "ThreadFuncs.h"

class ThreadManager
{
    std::deque <Sync *> flags;
    CRITICAL_SECTION workWithFlags;

    friend DWORD WINAPI threadGenerator(LPVOID);
    friend DWORD WINAPI threadPrinter(LPVOID);

    HANDLE printerThread;
    HANDLE generatorThread;

    const double showInterval;
    const double createNewThreadInterval;
    bool isStopGeneration;
    bool isStopPrinting;

public:
    ThreadManager(const double& showInterval, const double& createNewThreadInterval);
    ~ThreadManager();

    void generateNewThread();
    bool removeThread();            //kill random thread
    bool removeThread(int index);

    void runAll();
    void stopAll();

    int getNumOfThreads() const;
};

ThreadManager.cpp

#include "ThreadManager.h"

ThreadManager::ThreadManager(const double& showInterval, const double& createNewThreadInterval) :
    showInterval(showInterval), createNewThreadInterval(createNewThreadInterval), isStopGeneration(true), isStopPrinting(true)
{

    InitializeCriticalSection(&workWithFlags);

    printerThread = NULL;
    generatorThread = NULL;

}

int ThreadManager::getNumOfThreads() const
{
    return flags.size();
}

void ThreadManager::runAll()
{
    //run generation
    isStopGeneration = false;

    if (generatorThread != NULL)
    {
        return;
    }

    generatorThread = CreateThread(NULL, 0, threadGenerator, this, /*run immediately*/ 0, NULL);
    if (generatorThread == NULL)
    {
        //Stream::log("Error creating generation thread");
        isStopGeneration = true;
    }

    //run printing
    isStopPrinting = false;

    if (printerThread != NULL)
    {
        return;
    }

    printerThread = CreateThread(NULL, 0, threadPrinter, this, /*run immediately*/ 0, NULL);
    if (printerThread == NULL)
    {
        //Stream::log("Error creating printer thread");
        isStopPrinting = true;
    }
}

void ThreadManager::stopAll()
{
    //stop generation
    if (!generatorThread)
    {
        return;
    }

    isStopGeneration = true;

    WaitForSingleObject(generatorThread, INFINITE);

    CloseHandle(generatorThread);

    generatorThread = NULL;

    //stop printing
    if (!printerThread)
    {
        return;
    }

    isStopPrinting = true;

    WaitForSingleObject(printerThread, INFINITE);

    CloseHandle(printerThread);

    printerThread = NULL;
}

ThreadManager::~ThreadManager()
{
    stopAll();

    while (!flags.empty())
    {
        removeThread(flags.size() - 1);
    }

    DeleteCriticalSection(&workWithFlags);
}

void ThreadManager::generateNewThread()
{
    static int newIndex = 0;
    Sync* s = new Sync();

    s->index = newIndex;
    newIndex++;

    s->threadHandle = CreateThread(NULL, 0, threadChild, s, /*run immediately*/ 0, NULL);
    if (s->threadHandle == NULL)
    {
        //Stream::log("Error creating new thread");
        delete s;
        return;
    }

    EnterCriticalSection(&workWithFlags);
    flags.push_back(s);
    LeaveCriticalSection(&workWithFlags);
}

bool ThreadManager::removeThread(int index)
{
    EnterCriticalSection(&workWithFlags);

    if (flags.size() <= index || index < 0)
    {
        LeaveCriticalSection(&workWithFlags);
        return false;
    }

    Sync* s = flags[index];
    flags.erase(flags.begin() + index);

    s->operation = OPERATION_EXIT_THREAD;
    WakeConditionVariable(&s->canWork);

    WaitForSingleObject(s->threadHandle, INFINITE);

    delete s;

    LeaveCriticalSection(&workWithFlags);

    return true;
}

bool ThreadManager::removeThread()
{
    EnterCriticalSection(&workWithFlags);
    int size = flags.size();
    LeaveCriticalSection(&workWithFlags);

    if (!size)
    {
        return false;
    }

    return removeThread(rand() % size);
}

Sync.h

#pragma once

#include <windows.h>

#define OPERATION_EXIT_THREAD 1
#define OPERATION_START_WRITING_NAME 2

struct Sync
{
    CONDITION_VARIABLE canWork;
    CONDITION_VARIABLE isEndWork;
    HANDLE threadHandle;        //handle to thread
    int operation;              //operation type: 1 - exit, 2 - start writing name
    int index;                  //thread index

    Sync()
    {
        InitializeConditionVariable(&canWork);
        InitializeConditionVariable(&isEndWork);
        threadHandle = NULL;
        operation = 0;
        index = -1;
    }

    ~Sync()
    {
        if (threadHandle)
        {
            CloseHandle(threadHandle);
        }
    }
};

Updated:

Stack trace (that I understand that):


问:
Decimal integer to binary in C
Please give me some feedback on how to make my code better or more efficient. It should convert a decimal integer to binary.

```<code>#include <stdio.h>

binarydigits(int div, int dis)
{
    int numit;
    numit=0;

    do
    {
        ++numit;
        div /= dis;
    }
    while (div!=1);
    ++numit;
    return numit;
}

main()
{
    int x, nb, i;

    printf("\n Input an decimal integer number to be converted: ");
    scanf("%d", &x);
    fflush(stdin);

    if (x==0 || x==1)
    {
        printf("\n\n %d in binary : %d", x, x);
    }

    else
    {
        printf("\n\n %d in binary : ", x);
        nb = binarydigits(x, 2);
        // the function 'binarydigits' returns how many binary digits are needed to represent 'x'
        int remind[nb];
        // an array of 'nb' elements is declared. Each element of this array will hold a binary digit
        for(i=(nb-1) ; i>=0 ; --i, x/=2)
        {
            remind[i] = x%2;
        }
        //this 'for' structure saves the remainder of 'x/2' (x%2) in an element of the 'remind[nb]' array

        for (i=nb ; i>0 ; --i)
        {
            printf("%d", remind[nb-i]);
        }
        //this 'for' structure prints the elements of the 'remind[nb]' array in increasing order

    }

    getch();
    return 0;

}
</code>```

Any tips on how to make this better would be nice.

答:
Firstly, binarydigits should have a return type int. This is because you return an integer variable numit at the end of this function. Change your function header to:

```<code>int binarydigits(int div, int dis)
</code>```

Secondly, the main() function needs to have a return type int by definition in C, and C++ for that matter. Without it, your compiler will produce a warning, something similar to:

```<code>main.c:18:1: warning: return type defaults to 'int' [-Wimplicit-int]
 main()
 ^~~~
</code>```

Here is a snippet from the the C11 standard (ISO/IEC 9899:2011) on the definition of the main() function:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: - Return Type of main()

```<code>int main(void) { /* ... */ }
</code>```

Thirdly, you should remove fflush(stdin) because using the fflush() for stdint is undefined behavior as it is not a part of standard C. From C11 7.21.5.2, fflush works only with output/update stream, not input stream:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined. - fflush(stdin)

Title: Decimal integer to binary in C

Body:
Please give me some feedback on how to make my code better or more efficient. It should convert a decimal integer to binary.

#include <stdio.h>

binarydigits(int div, int dis)
{
    int numit;
    numit=0;

    do
    {
        ++numit;
        div /= dis;
    }
    while (div!=1);
    ++numit;
    return numit;
}

main()
{
    int x, nb, i;

    printf("\n Input an decimal integer number to be converted: ");
    scanf("%d", &x);
    fflush(stdin);

    if (x==0 || x==1)
    {
        printf("\n\n %d in binary : %d", x, x);
    }

    else
    {
        printf("\n\n %d in binary : ", x);
        nb = binarydigits(x, 2);
        // the function 'binarydigits' returns how many binary digits are needed to represent 'x'
        int remind[nb];
        // an array of 'nb' elements is declared. Each element of this array will hold a binary digit
        for(i=(nb-1) ; i>=0 ; --i, x/=2)
        {
            remind[i] = x%2;
        }
        //this 'for' structure saves the remainder of 'x/2' (x%2) in an element of the 'remind[nb]' array

        for (i=nb ; i>0 ; --i)
        {
            printf("%d", remind[nb-i]);
        }
        //this 'for' structure prints the elements of the 'remind[nb]' array in increasing order

    }

    getch();
    return 0;

}

Any tips on how to make this better would be nice.

Body:
Firstly, binarydigits should have a return type int. This is because you return an integer variable numit at the end of this function. Change your function header to:

int binarydigits(int div, int dis)

Secondly, the main() function needs to have a return type int by definition in C, and C++ for that matter. Without it, your compiler will produce a warning, something similar to:

main.c:18:1: warning: return type defaults to 'int' [-Wimplicit-int]
 main()
 ^~~~

Here is a snippet from the the C11 standard (ISO/IEC 9899:2011) on the definition of the main() function:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: - Return Type of main()

int main(void) { /* ... */ }

Thirdly, you should remove fflush(stdin) because using the fflush() for stdint is undefined behavior as it is not a part of standard C. From C11 7.21.5.2, fflush works only with output/update stream, not input stream:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined. - fflush(stdin)


问:
How to check if a nested list contain only empty strings
In pyqt I have a qtableview which a user can edit. If the users makes a change to the table, the table will be copied when the user is done. If no changes are made, the table is skipped. The table is filled with empty strings i.e:

```<code>table = [["","",""],["","",""]]
</code>```

I want to check if the table contains only "", and if it does, ignore it. If it doesnt, i.e. contains a "1", some code runs on the list.
Now I have a working code but its not very pythonic and I wonder how I can improve it. My code is as follows:

```<code>tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing
</code>```

答:
To check if any element in any of the sublist fulfills the condition you could use any and a nested generator expression:

```<code>tabell1 = [["","",""],["","",""]]
if any(item for sublist in tabell1 for item in sublist):
    # do the thing
</code>```

This also has the advantage that it stops as soon as it finds one not-empty string! Your method would continue to search until it checked all items in all sublists.

Empty strings are considered False and every string containing at least one item is considered True. However you could also explicitly compare to empty strings:

```<code>tabell1 = [["","",""],["","",""]]
if any(item != "" for sublist in tabell1 for item in sublist):
    # do the thing
</code>```

Body:
In pyqt I have a qtableview which a user can edit. If the users makes a change to the table, the table will be copied when the user is done. If no changes are made, the table is skipped. The table is filled with empty strings i.e:

table = [["","",""],["","",""]]

I want to check if the table contains only "", and if it does, ignore it. If it doesnt, i.e. contains a "1", some code runs on the list.
Now I have a working code but its not very pythonic and I wonder how I can improve it. My code is as follows:

tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing

Body:
To check if any element in any of the sublist fulfills the condition you could use any and a nested generator expression:

tabell1 = [["","",""],["","",""]]
if any(item for sublist in tabell1 for item in sublist):
    # do the thing

This also has the advantage that it stops as soon as it finds one not-empty string! Your method would continue to search until it checked all items in all sublists.

Empty strings are considered False and every string containing at least one item is considered True. However you could also explicitly compare to empty strings:

tabell1 = [["","",""],["","",""]]
if any(item != "" for sublist in tabell1 for item in sublist):
    # do the thing


问:
Unity Linux package export is modifying my DLL
Just to give some context, I'm trying to create a build server on Ubuntu 16.04 to build a package for the Unity Asset store.

I'm using mcs to export some of our code (the code that we don't want user facing) into a dll, using the following command:

```<code>mcs -debug+ -debug:full -optimize- -codepage:utf8 -sdk:2 -lib:/opt/Unity/Editor/Data/MonoBleedingEdge/lib/mono/2.0-api/ -t:library -define:DEBUG -define:RELEASE_IS_TRIAL -define:DEBUGGER_IS_DISABLED  -out:<path to dll> -reference:<required extra references> -recurse:<path to source>/*.cs
</code>```

I then put this inside a new unity project and export that project using the following command:

```<code>/opt/Unity/Editor/Unity -quit -batchmode -nographics -serial <serial> -username <username> -password "" -projectPath <path to project> -exportPackage "Assets" <path to preferred output location>.unitypackage
</code>```

If I then import this package in unity on windows, I get a bunch of errors along the lines of:

```<code>The type or namespace name A does not exist in the namespace B (are you missing an assembly reference?)
</code>```

Here A and B are my own defined types and namespaces.. i.e. the dll is not being loaded. There's nothing wrong with this dll though. In particular, if i run the above mcs command, take that output dll and replace the one in the imported package, everything imports fine. If i look at the Assembly attributes of the dll as it was exported in the unitypackage, and the dll straight from mcs (using ILSpy), I can see that the one exported by unity has an extra attribute:

```<code>[assembly: UnityAPICompatibilityVersion("5.6.0xb10Linux")]
</code>```

I'm highly suspicious that this is the attribute causing the problem, but I don't know how to stop Unity from exporting the dll this way so that the unitypackage can be platform agnostic. Any ideas?

答: It turns out that I had a later version of Unity running on the Linux machine than on my Windows machine. There were incompatibility errors in the code because I was using obsolete functions from the Unity API as far as the Linux machine was concerned. So when it built the package it created a screwy dll. Whoops.</p>

Body:
Just to give some context, I'm trying to create a build server on Ubuntu 16.04 to build a package for the Unity Asset store.

I'm using mcs to export some of our code (the code that we don't want user facing) into a dll, using the following command:

mcs -debug+ -debug:full -optimize- -codepage:utf8 -sdk:2 -lib:/opt/Unity/Editor/Data/MonoBleedingEdge/lib/mono/2.0-api/ -t:library -define:DEBUG -define:RELEASE_IS_TRIAL -define:DEBUGGER_IS_DISABLED  -out:<path to dll> -reference:<required extra references> -recurse:<path to source>/*.cs

I then put this inside a new unity project and export that project using the following command:

/opt/Unity/Editor/Unity -quit -batchmode -nographics -serial <serial> -username <username> -password "" -projectPath <path to project> -exportPackage "Assets" <path to preferred output location>.unitypackage

If I then import this package in unity on windows, I get a bunch of errors along the lines of:

The type or namespace name A does not exist in the namespace B (are you missing an assembly reference?)

Here A and B are my own defined types and namespaces.. i.e. the dll is not being loaded. There's nothing wrong with this dll though. In particular, if i run the above mcs command, take that output dll and replace the one in the imported package, everything imports fine. If i look at the Assembly attributes of the dll as it was exported in the unitypackage, and the dll straight from mcs (using ILSpy), I can see that the one exported by unity has an extra attribute:

[assembly: UnityAPICompatibilityVersion("5.6.0xb10Linux")]

I'm highly suspicious that this is the attribute causing the problem, but I don't know how to stop Unity from exporting the dll this way so that the unitypackage can be platform agnostic. Any ideas?


问:
How do I make a header stay under a centered picture in Bootstrap 3?
This is my first time asking of Stack Overflow so I'm sorry if the formatting isn't perfect. Anyways, I'm working on a website which uses Bootstrap 3. It has an image that is centered in the middle of the page vertically and horizontally. It also has a background image. I am trying to put a header under the image in the center but the header goes to the top of the page. There is a fixed nav-bar on the bottom of the page.

Here's the HTML:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
                <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <title>
            App
        </title>
        <style>
            html {
                background-image: url("gradiant.png");
            }
            .logo {
                position: absolute;
   top: 40%;
   left: 50%;
   width: 500px;
   height: 500px;
   margin-top: -216.5px;
   margin-left: -236.25px;
            }
            .nav-pills li a {
                color: white;
                font-size: 250%;
            }
                .nav-pills li a {
    background-color: transparent;
    color: #ffffff;
    transition: all .5s;
border: 2px solid transparent;
}
.nav-pills li a:hover{
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;

}
.dropdown{
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;

}
.nav-pills > li > .dropdown-menu {
    background-color: transparent;
    border-color: #ffffff;
    }
    .dropdown-toggle {
        background-color: transparent !important;
    }
.dropdown-toggle:active, .open .dropdown-toggle {
    background-color: transparent !important;
    color: white !important;
    border-color: #ffffff !important;
    }
.nav-pills {
    float:none;
    margin:0 auto;
    display: block;
    text-align: center;
}

.nav-pills > li {
    display: inline-block;
    float:none;
}
h1 {
     position: absolute;
     color: #ffffff;
}
  </style>
    </head>
    <body>
 <img alt="App" src="app.png" width=472.5 height=433 class="logo" align="middle" >
 <h1>App</h1>
 <ul class="nav nav-pills navbar-fixed-bottom">

          <li><a href="index.html">Home</a></li>

   <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="app.html">App</a></li>
          </ul>
        </li>

    <ul class="dropdown-menu">

    </ul>
  </li>
                <li><a href="contact.html">Contact</a></li>

</ul>
    </body>
</html>
</code>```

答:
This is not a Bootstrap-specific answer, but what you can do is create a container for the logo and apply the CSS, you're currently applying to the image, to the container. Then just put the heading below the image in the container:

html {
    background-image: url("gradiant.png");
}
.logo-container {
    position: absolute;
    top: 40%;
    left: 50%;
    width: 500px;
    height: 500px;
    margin-top: -216.5px;
    margin-left: -236.25px;
}
  .logo-container img {
    width:100%;
  }
.nav-pills li a {
    color: white;
    font-size: 250%;
}
.nav-pills li a {
    background-color: transparent;
    color: #ffffff;
    transition: all .5s;
    border: 2px solid transparent;
}
.nav-pills li a:hover {
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;
}
.dropdown {
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;
}
.nav-pills > li > .dropdown-menu {
    background-color: transparent;
    border-color: #ffffff;
}
.dropdown-toggle {
    background-color: transparent !important;
}
.dropdown-toggle:active,
.open .dropdown-toggle {
    background-color: transparent !important;
    color: white !important;
    border-color: #ffffff !important;
}
.nav-pills {
    float: none;
    margin: 0 auto;
    display: block;
    text-align: center;
}
.nav-pills > li {
    display: inline-block;
    float: none;
}
h1 {
     position: absolute;
     color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="logo-container">
  <img alt="App" src="http://lorempixel.com/500/500/" class="logo" align="middle" >
  <h2>Title goes here</h2>
</div>
<h1>App</h1>
<ul class="nav nav-pills navbar-fixed-bottom">
   <li>Home</li>
   <li class="dropdown">
      Apps <span class="caret"></span>
      <ul class="dropdown-menu">
         <li>App</li>
      </ul>
   </li>
   <li>
     <ul class="dropdown-menu">
     </ul>
   </li>
   <li>Contact</li>
</ul></code>```

Body:
This is my first time asking of Stack Overflow so I'm sorry if the formatting isn't perfect. Anyways, I'm working on a website which uses Bootstrap 3. It has an image that is centered in the middle of the page vertically and horizontally. It also has a background image. I am trying to put a header under the image in the center but the header goes to the top of the page. There is a fixed nav-bar on the bottom of the page.

Here's the HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <title>
            App
        </title>

App

Home

          Apps

App

Contact

Body:
This is not a Bootstrap-specific answer, but what you can do is create a container for the logo and apply the CSS, you're currently applying to the image, to the container. Then just put the heading below the image in the container:

html {
    background-image: url("gradiant.png");
}
.logo-container {
    position: absolute;
    top: 40%;
    left: 50%;
    width: 500px;
    height: 500px;
    margin-top: -216.5px;
    margin-left: -236.25px;
}
  .logo-container img {
    width:100%;
  }
.nav-pills li a {
    color: white;
    font-size: 250%;
}
.nav-pills li a {
    background-color: transparent;
    color: #ffffff;
    transition: all .5s;
    border: 2px solid transparent;
}
.nav-pills li a:hover {
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;
}
.dropdown {
    background-color: transparent;
    color: #ffffff;
    border-color: #ffffff;
}
.nav-pills > li > .dropdown-menu {
    background-color: transparent;
    border-color: #ffffff;
}
.dropdown-toggle {
    background-color: transparent !important;
}
.dropdown-toggle:active,
.open .dropdown-toggle {
    background-color: transparent !important;
    color: white !important;
    border-color: #ffffff !important;
}
.nav-pills {
    float: none;
    margin: 0 auto;
    display: block;
    text-align: center;
}
.nav-pills > li {
    display: inline-block;
    float: none;
}
h1 {
     position: absolute;
     color: #ffffff;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="logo-container">
  <img alt="App" src="http://lorempixel.com/500/500/" class="logo" align="middle" >
  <h2>Title goes here</h2>
</div>
<h1>App</h1>
<ul class="nav nav-pills navbar-fixed-bottom">
   <li><a href="index.html">Home</a></li>
   <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps <span class="caret"></span></a>
      <ul class="dropdown-menu">
         <li><a href="app.html">App</a></li>
      </ul>
   </li>
   <li>
     <ul class="dropdown-menu">
     </ul>
   </li>
   <li><a href="contact.html">Contact</a></li>
</ul>


问:
Remove higher order derivatives from Maple expression
Is there a simple way of only keeping (partial) derivatives up to some order in a Maple expression? For example, suppose I put

```<code>f(x) := (g(x)+diff(g(x),x))*(h(x)+diff(h(x),x))
</code>```

The full expression for f' is

```<code>f'=g'h+gh'+2g'h'+gh''+g''h+g''h'+g'h''
</code>```

and if I keep only the terms up to first order derivative I have

```<code>f'=g'h+gh'+2g'h'.
</code>```

Is there a way in Maple to first do

```<code>diff(f(x),x)
</code>```

and then remove by some command all derivatives of higher order than 1 (in this case)?

答:
One solution involves converting to operator notation for the derivatives.

```<code>f := (g(x)+diff(g(x),x))*(h(x)+diff(h(x),x));
Df := convert( diff(f, x), D);
df := eval(Df,D@@2=0);
convert(df,diff);
</code>```

The key here is that in operator form it is easy to get a hold of the second derivatives since they are acted on by the D@@2 operator.  If you replace that operator with the 0 operator, it maps all the second derivative terms to zero.  If you want to remove higher order terms, you have to do something like:

```<code>eval(Df,{seq(D@@i=0, i=2..5)});
</code>```

If you want to do this with partial derivatives instead.

```<code>f := (g(x, y)+diff(g(x, y), x))*(h(x, y)+diff(h(x, y), x));
Df := convert(diff(f, x), D);
df := eval(Df, D[1, 1] = 0);
convert(df, diff);
</code>```

In the context of partials, the differential operator is indexed with a sequence rather than composed.  So here, D[1,2] will be the partial wrt x followed by the partial wrt y.

Body:
Is there a simple way of only keeping (partial) derivatives up to some order in a Maple expression? For example, suppose I put

f(x) := (g(x)+diff(g(x),x))*(h(x)+diff(h(x),x))

The full expression for f' is

f'=g'h+gh'+2g'h'+gh''+g''h+g''h'+g'h''

and if I keep only the terms up to first order derivative I have

f'=g'h+gh'+2g'h'.

Is there a way in Maple to first do

diff(f(x),x)

and then remove by some command all derivatives of higher order than 1 (in this case)?

Body:
One solution involves converting to operator notation for the derivatives.

f := (g(x)+diff(g(x),x))*(h(x)+diff(h(x),x));
Df := convert( diff(f, x), D);
df := eval(Df,D@@2=0);
convert(df,diff);

The key here is that in operator form it is easy to get a hold of the second derivatives since they are acted on by the D@@2 operator.  If you replace that operator with the 0 operator, it maps all the second derivative terms to zero.  If you want to remove higher order terms, you have to do something like:

eval(Df,{seq(D@@i=0, i=2..5)});

If you want to do this with partial derivatives instead.

f := (g(x, y)+diff(g(x, y), x))*(h(x, y)+diff(h(x, y), x));
Df := convert(diff(f, x), D);
df := eval(Df, D[1, 1] = 0);
convert(df, diff);

In the context of partials, the differential operator is indexed with a sequence rather than composed.  So here, D[1,2] will be the partial wrt x followed by the partial wrt y.


问:
Replace two or three parts of a URL in a JavaScript bookmarklet

Original URL

https://website.org/directory/page.php

Updated URL

https://sub1.sub2.site.com/files/content?site=mysite&path=/directory/page.html

I already have this great bookmarklet for switching the subdomain from a production server to development.

javascript:location.href=location.protocol+"//"+"webproto"+"."+(location.host.split(".").length==3?location.host.split(".").slice(1,location.host.split(".").length).join("."):location.host)+location.pathname+location.search;

But I cannot figure out how to take this to the next level by

replacing the subdomain with multiple subdomains

replacing the domain name extension

adding the path with query and params

and switching the extension

答:
So putting this into a bookmarklet while making it robust is non trivial.  Here's my solution.

install webpack with npm install -g webpack

create a file layout like this:

```<code>project/
  bookmarklet.js
  download/
     urlMunge.js
</code>```

The contents of bookmarklet.js

```<code>javascript: (function () {
   var jsCode = document.createElement('script');
   jsCode.setAttribute('src', 'https://YOUR_SERVER/bundle.js');
   document.body.appendChild(jsCode);
}());
</code>```

the contents of urlMunge.js

```<code>// put all in a function to make sure that we don't mess up whatever page
// we are on.
var urlMunge = function urlMunge() {
  var URL = require('url-parse');
  var EXT = '.html';

  // https://sub1.sub2.site.com/files/content?site=mysite&path=/directory/page.html
  test1 = window.location;
  var sourceUrl = new URL(test1);
  var formattedUrl = new URL('https://sub1.sub2.site.com/files/content');
  var pathname = sourceUrl.pathname;
  var host = sourceUrl.host;
  var query = {
    query: sourceUrl.query,
    path: pathname.slice(0, pathname.lastIndexOf('.')) + EXT,
    host: host.slice(0, host.lastIndexOf('.')) + '.com',
  }

  formattedUrl.set('query', query);

  console.log(formattedUrl.toString());
}

urlMunge();
</code>```

add the url-parse library.  cd into the download directory and run npm install url-parse which will create a node_modules directory with url-parse and its dependencies.

in the download directory run webpack urlMunge.js ../bundle.js which will create bundle.js with both our code and the url-parse lib.

place bundle.js into a webserver where your bookmarklet can load it and test away.  You'll need to look in the console of your browser to see the output of urlMunge.

Body:
So putting this into a bookmarklet while making it robust is non trivial.  Here's my solution.

install webpack with npm install -g webpack

create a file layout like this:

project/
  bookmarklet.js
  download/
     urlMunge.js

The contents of bookmarklet.js

javascript: (function () {
   var jsCode = document.createElement('script');
   jsCode.setAttribute('src', 'https://YOUR_SERVER/bundle.js');
   document.body.appendChild(jsCode);
}());

the contents of urlMunge.js

// put all in a function to make sure that we don't mess up whatever page
// we are on.
var urlMunge = function urlMunge() {
  var URL = require('url-parse');
  var EXT = '.html';

  // https://sub1.sub2.site.com/files/content?site=mysite&path=/directory/page.html
  test1 = window.location;
  var sourceUrl = new URL(test1);
  var formattedUrl = new URL('https://sub1.sub2.site.com/files/content');
  var pathname = sourceUrl.pathname;
  var host = sourceUrl.host;
  var query = {
    query: sourceUrl.query,
    path: pathname.slice(0, pathname.lastIndexOf('.')) + EXT,
    host: host.slice(0, host.lastIndexOf('.')) + '.com',
  }

  formattedUrl.set('query', query);

  console.log(formattedUrl.toString());
}

urlMunge();

add the url-parse library.  cd into the download directory and run npm install url-parse which will create a node_modules directory with url-parse and its dependencies.

in the download directory run webpack urlMunge.js ../bundle.js which will create bundle.js with both our code and the url-parse lib.

place bundle.js into a webserver where your bookmarklet can load it and test away.  You'll need to look in the console of your browser to see the output of urlMunge.


问:
UIScrollView contentSize doesn't work
I have a problem with my UIScollView who scrolls vertically. I just want my ScollView scroll horizontally. I've tried to change the contentSize but that doesn't worked.

I use constraints, and this code :

```<code>var plugeeNews : [Plugs]?

var topNewsScrollView : UIScrollView = {
        var scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 75))
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.backgroundColor = .gray
        scrollView.isDirectionalLockEnabled = true
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()

func setupViewInTopNewsScrollView() {
        for i in 0..<plugeeNews.count {
            let xPosition = screenSize.width * CGFloat(i)
            let myView = TopNewsCell(frame: CGRect(x: xPosition, y: 0, width: screenSize.width , height: heightOfNewsCell))
            myView.label.text = plugeeNews[i]
            myView.randomBackgroundColor(number: i)
            topNewsScrollView.contentSize = CGSize(width: topNewsScrollView.frame.width * CGFloat(i + 1),height:  heightOfNewsCell)
            topNewsScrollView.addSubview(myView)
        }
    }
</code>```

This is the height constraint of my UIScrollView :

```<code>...
        topNewsScrollView.heightAnchor.constraint(equalToConstant: heightOfNewsCell).isActive = true
</code>```

And this is the result :

And I don't want the gray view below the white/gray views on the UIScollView, i just want to swipe between my views horizontally.

答:
Set the content size:</p>

```<code>scrollContainer.contentSize = CGSize(width:10000, height:50)
</code>```

Title: UIScrollView contentSize doesn't work

Body:
I have a problem with my UIScollView who scrolls vertically. I just want my ScollView scroll horizontally. I've tried to change the contentSize but that doesn't worked.

I use constraints, and this code :

var plugeeNews : [Plugs]?

var topNewsScrollView : UIScrollView = {
        var scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 75))
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.backgroundColor = .gray
        scrollView.isDirectionalLockEnabled = true
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()

func setupViewInTopNewsScrollView() {
        for i in 0..<plugeeNews.count {
            let xPosition = screenSize.width * CGFloat(i)
            let myView = TopNewsCell(frame: CGRect(x: xPosition, y: 0, width: screenSize.width , height: heightOfNewsCell))
            myView.label.text = plugeeNews[i]
            myView.randomBackgroundColor(number: i)
            topNewsScrollView.contentSize = CGSize(width: topNewsScrollView.frame.width * CGFloat(i + 1),height:  heightOfNewsCell)
            topNewsScrollView.addSubview(myView)
        }
    }

This is the height constraint of my UIScrollView :

...
        topNewsScrollView.heightAnchor.constraint(equalToConstant: heightOfNewsCell).isActive = true

And this is the result :

And I don't want the gray view below the white/gray views on the UIScollView, i just want to swipe between my views horizontally.

Body:
Set the content size:

scrollContainer.contentSize = CGSize(width:10000, height:50)


问:
Applying a UDF into a for loop - Python
Example of PDF: "Smith#00$Consolidated_Performance.pdf"

The goal is to add a bookmark to page 1 of each PDF based on the filename.

(Bookmark name in example would be "Consolidated Performance")

```<code>import os
from openpyxl import load_workbook
from PyPDF2 import PdfFileMerger

cdir = "Directory of PDF" # Current directory
pdfcdir = [filename for filename in os.listdir(cdir) if filename.endswith(".pdf")]

def addbookmark(f):
    output = PdfFileMerger()
    name = os.path.splitext(os.path.basename(f))[0] # Split filename from .pdf extension
    dp = name.index("$") + 1 # Find position of $ sign
    bookmarkname = name[dp:].replace("_", " ") # replace underscores with spaces
    output.addBookmark(bookmarkname, 0, parent=None) # Add bookmark
    output.append(open(f, 'rb'))
    output.write(open(f, 'wb'))

for f in pdfcdir:
    addbookmark(f)
</code>```

The UDF works fine when applied to individual PDFs, but it won't add the bookmarks when put into the loop at the bottom of the code. Any ideas on how to make the UDF loop through all PDFs within pdfcdir?

答:
I'm pretty sure that the issue you're having has nothing to do with the loop. Rather, you're passing just the filenames and not including the directory path. It's trying to open these files in the script's current working directory (the directory the script is in, by default) rather than in the directory you read the filenames from.

So, join the directory name with each file name when calling your function.

```<code>for f in pdfcdir:
    addbookmark(os.path.join(cdir, f))
</code>```

Title: Applying a UDF into a for loop - Python

Body:
Example of PDF: "Smith#00$Consolidated_Performance.pdf"

The goal is to add a bookmark to page 1 of each PDF based on the filename.

(Bookmark name in example would be "Consolidated Performance")

import os
from openpyxl import load_workbook
from PyPDF2 import PdfFileMerger

cdir = "Directory of PDF" # Current directory
pdfcdir = [filename for filename in os.listdir(cdir) if filename.endswith(".pdf")]

def addbookmark(f):
    output = PdfFileMerger()
    name = os.path.splitext(os.path.basename(f))[0] # Split filename from .pdf extension
    dp = name.index("$") + 1 # Find position of $ sign
    bookmarkname = name[dp:].replace("_", " ") # replace underscores with spaces
    output.addBookmark(bookmarkname, 0, parent=None) # Add bookmark
    output.append(open(f, 'rb'))
    output.write(open(f, 'wb'))

for f in pdfcdir:
    addbookmark(f)

The UDF works fine when applied to individual PDFs, but it won't add the bookmarks when put into the loop at the bottom of the code. Any ideas on how to make the UDF loop through all PDFs within pdfcdir?

Body:
I'm pretty sure that the issue you're having has nothing to do with the loop. Rather, you're passing just the filenames and not including the directory path. It's trying to open these files in the script's current working directory (the directory the script is in, by default) rather than in the directory you read the filenames from.

So, join the directory name with each file name when calling your function.

for f in pdfcdir:
    addbookmark(os.path.join(cdir, f))


问:
Load Python 2 .npy file in Python 3
I'm trying to load /usr/share/matplotlib/sample_data/goog.npy:

```<code>datafile = matplotlib.cbook.get_sample_data('goog.npy', asfileobj=False)
np.load(datafile)
</code>```

It's fine in Python 2.7, but raises an exception in Python 3.4:

```<code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 1: ordinal not in range(128)
</code>```

I assume it has something to do with bytes/str/unicode inconsistency between Python 2 and 3, but have no idea how to get through.

Question:

How to load a .npy file (NumPy data) from Python 2 in Python 3?

答:
In python 3.5 with numpy 1.10.4, using the following command works for me ;

```<code>D = np.load(file, encoding = 'latin1')
</code>```

It fails with the same error message when I don't specify the encoding.

Title: Load Python 2 .npy file in Python 3

Body:
I'm trying to load /usr/share/matplotlib/sample_data/goog.npy:

datafile = matplotlib.cbook.get_sample_data('goog.npy', asfileobj=False)
np.load(datafile)

It's fine in Python 2.7, but raises an exception in Python 3.4:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 1: ordinal not in range(128)

I assume it has something to do with bytes/str/unicode inconsistency between Python 2 and 3, but have no idea how to get through.

Question:

How to load a .npy file (NumPy data) from Python 2 in Python 3?

Body:
In python 3.5 with numpy 1.10.4, using the following command works for me ;

D = np.load(file, encoding = 'latin1')

It fails with the same error message when I don't specify the encoding.


问:
VSTO Click-Once Certificate breaks TFS 2015 build
I develop an Excel 2010 addin. Therefor I have a click-once installer with a corresponding certificate. Everything works fine on my machine but now I have to build it on a TFS 2015.

When ever the signing is switch on, I get messages telling me:

[error]C:\Program Files
  (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(2718,5):
  Error MSB3326: Cannot import the following key file: . The key file
  may be password protected. To correct this, try to import the
  certificate again or import the certificate manually into the current
  user's personal certificate store.

C:\Program Files
  (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(2718,5):
  error MSB3326: Cannot import the following key file: . The key file
  may be password protected. To correct this, try to import the
  certificate again or import the certificate manually into the current
  user's personal certificate store.

[error]C:\Program Files
  (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(2718,5):
  Error MSB3321: Importing key file "My CERT.pfx" was
  canceled.

If I have it switched off, then I get another message:

"C:\Program Files
  (x86)\MSBuild\Microsoft\VisualStudio\v12.0\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets(159,9):
  Error : Cannot build because the ClickOnce manifest signing option is
  not selected. To select this option, open the project property pages,
  click the Signing tab, and then select "Sign the ClickOnce
  manifests.""

In both ways the build breaks and I don't understand why. I even deleted the certificate and removed every bit of information about signing from the cproj file, without any success.

I would like to have a build without the signing. How can I achive thise?

答:
I had VSTO Outlook add-in working with TFS online fine until I renamed the add-in project and started to experience exactly the same build errors today.

Following steps helped me:

Untick “Sign the ClickOnce manifests” and “Sign the assembly” options.

Delete all pfx files from the project.

Remove all manifest related tags from csproj.

“Create Test Certificate” without entering anything into password boxes and choosing sha256RSA algorithm.

Remove “*.pfx” files from .gitignore (I use GIT as source control).

Tick “Sign the ClickOnce manifests” option.

Check-in all changes together with new “…_TemporaryKey.pfx” file.

Now I only get following warning in TFS build logs, but at least the build doesn’t fail anymore :-)

“warning MSB3327: Unable to find code signing certificate in the current user's Windows certificate store. To correct this, either disable signing of the ClickOnce manifest or install the certificate into the certificate store.”

I hope this will help you too!


问:
Swift 3 reusable post method in helper
I am working on swift 3 application and want to build login system using REST API. First I wanted a way to post data to server (PHP + MYSQL) with parameters so I found this post.

HTTP Request in Swift with POST method

Now I wanted place this code in a method as helper so I can utilise this method from anywhere in app. Hence followed this way:

Where to put reusable functions in IOS Swift?

Current code is as follow:

```<code>import Foundation

class Helper {

static func postData(resource: String, params: [String: String]) -> [String:String] {

    var request = URLRequest(url: URL(string: "http://localsite.dev/api/\(resource)")!)
    request.httpMethod = "POST"

    var qryString: String = "?key=abcd"
    for (paramKey, paramVal) in params {
        qryString = qryString.appending("&\(paramKey)=\(paramVal)")
    }

    request.httpBody = qryString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("Error")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("Error on HTTP")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
        print("success and here is returned data \(responseString)")
    }

    task.resume()

    return ["data" : "some data"]

}
}
</code>```

Call this using

```<code>let loginDetails: [String: String] = ["email": emailTxt.text!, "pass": passTxt.text!]
Helper.postData(resource: "login", params: loginDetails)
</code>```

In above method rather then printing data I want to return data as per below 4 conditions.

1.If error in request data then I want to return as

```<code>[“status”: false, “message”: “Something wrong with request”]
</code>```

2.If error in HTTP request

```<code>[“status”: false, “message”: “Resource not found”]
</code>```

3.If login fail

```<code>[“status”: false, “message”: “Wrong login details”]
</code>```

4.If login success

```<code>[“status”: true, “message”: “Login success”]
</code>```

答:
If you want to use a third party library for handling HTTP request, I strongly recommend Alamofire.

When I wanna handle HTTP requests I usually create a singleton class:

```<code>class HttpRequestHelper {
   static let shared = HttpRequestHelper()

   func post(to url: URL, params: [String: String], headers: [String: String], completion: (Bool, String) -> ()){
         //Make the http request
         //if u got a successful response
         // parse it to JSON and return it via completion handle
         completion(true, message)
         //if response is not successful
         completion(false, message)

   }

}
</code>```

And you can use it everywhere:

```<code>class AnotherClass: UIViewController {
    HttpRequestHelper.shared.post(to: url, params: [:], header: [:],
    completion:{
        success, message in
          print(success)
          print(message)
    })
}
</code>```

To the POST method more reusable and not just specific to an endpoint, I usually make the completion handler params as Bool, JSON. And then I handle the JSON response from wherever I call the method.

Oh and I use SwiftyJson to parse json, it's the simplest.

Title: Swift 3 reusable post method in helper

Body:
I am working on swift 3 application and want to build login system using REST API. First I wanted a way to post data to server (PHP + MYSQL) with parameters so I found this post.

HTTP Request in Swift with POST method

Now I wanted place this code in a method as helper so I can utilise this method from anywhere in app. Hence followed this way:

Where to put reusable functions in IOS Swift?

Current code is as follow:

import Foundation

class Helper {

static func postData(resource: String, params: [String: String]) -> [String:String] {

    var request = URLRequest(url: URL(string: "http://localsite.dev/api/\(resource)")!)
    request.httpMethod = "POST"

    var qryString: String = "?key=abcd"
    for (paramKey, paramVal) in params {
        qryString = qryString.appending("&\(paramKey)=\(paramVal)")
    }

    request.httpBody = qryString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("Error")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("Error on HTTP")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
        print("success and here is returned data \(responseString)")
    }

    task.resume()

    return ["data" : "some data"]

}
}

Call this using

let loginDetails: [String: String] = ["email": emailTxt.text!, "pass": passTxt.text!]
Helper.postData(resource: "login", params: loginDetails)

In above method rather then printing data I want to return data as per below 4 conditions.

1.If error in request data then I want to return as

[“status”: false, “message”: “Something wrong with request”]

2.If error in HTTP request

[“status”: false, “message”: “Resource not found”]

3.If login fail

[“status”: false, “message”: “Wrong login details”]

4.If login success

[“status”: true, “message”: “Login success”]

Body:
If you want to use a third party library for handling HTTP request, I strongly recommend Alamofire.

When I wanna handle HTTP requests I usually create a singleton class:

class HttpRequestHelper {
   static let shared = HttpRequestHelper()

   func post(to url: URL, params: [String: String], headers: [String: String], completion: (Bool, String) -> ()){
         //Make the http request
         //if u got a successful response
         // parse it to JSON and return it via completion handle
         completion(true, message)
         //if response is not successful
         completion(false, message)

   }

}

And you can use it everywhere:

class AnotherClass: UIViewController {
    HttpRequestHelper.shared.post(to: url, params: [:], header: [:],
    completion:{
        success, message in
          print(success)
          print(message)
    })
}

To the POST method more reusable and not just specific to an endpoint, I usually make the completion handler params as Bool, JSON. And then I handle the JSON response from wherever I call the method.

Oh and I use SwiftyJson to parse json, it's the simplest.


问:
custom post types wordpress
I am wanting to create a custom post type called testimonials, for this I am wanting to allow the administrator that chance to add a company name/username and what testimonial they have given, I understand I can do this by declaring a custom post-type in my functions.php file, however it does not seem to work and all I get is the normal post fields, can someone tell me where I am going wrong, or how I would do this please?

```<code> function testimonials_register() {
 $args = array(
  'label' => __('Testimonials'),
  'singular_label' => __('Testimonial'),
  'public' => true,
  'show_ui' => true,
  'capability_type' => false,
  'hierarchical' => false,
  'rewirte' => true,
  'supports' => array('title', 'editor')
 );

 register_post_type('testimonial', $args);
}
</code>```

答: You spelled rewrite wrong, for starters.</p>

ContentLicense: CC BY-SA 2.5

Title: custom post types wordpress

Body:
I am wanting to create a custom post type called testimonials, for this I am wanting to allow the administrator that chance to add a company name/username and what testimonial they have given, I understand I can do this by declaring a custom post-type in my functions.php file, however it does not seem to work and all I get is the normal post fields, can someone tell me where I am going wrong, or how I would do this please?

 function testimonials_register() {
 $args = array(
  'label' => __('Testimonials'),
  'singular_label' => __('Testimonial'),
  'public' => true,
  'show_ui' => true,
  'capability_type' => false,
  'hierarchical' => false,
  'rewirte' => true,
  'supports' => array('title', 'editor')
 );

 register_post_type('testimonial', $args);
}


问:
Convert SQL Server result set into string
I am getting the result in SQL Server as

```<code>SELECT StudentId FROM Student WHERE condition = xyz
</code>```

I am getting the output like

```
StudentId
1236

7656

8990
........
```

The output parameter of the stored procedure is @studentId string and I want the return statement as

```<code>1236, 7656, 8990.
</code>```

How can I convert the output in the single string?

I am returning single column [ie. StudentId]

答:
Use the CONCAT function to avoid conversion errors:

```<code>DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = CONCAT(COALESCE(@StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID
</code>```

Body:
I am getting the result in SQL Server as

SELECT StudentId FROM Student WHERE condition = xyz

I am getting the output like

StudentId
1236

7656

8990
........

The output parameter of the stored procedure is @studentId string and I want the return statement as

1236, 7656, 8990.

How can I convert the output in the single string?

I am returning single column [ie. StudentId]

Body:
Use the CONCAT function to avoid conversion errors:

DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = CONCAT(COALESCE(@StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID


问:
ASP.NET MVC Get value of div by using ID in Controller
When the user clicks a button, the following HTML gets added to the page by Javascript, and the value of IncrNumber increases each time the button is clicked, so the first click would produce divs with the following ID's: (start0, end0, comm0) and the second click would produce ID's (start1, end1, comm1) and so on.

```<code>Start: <input type="text" class="form-control" id="start' + IncrNumber + '"/>

End: <input type="text" class="form-control" id="end' + IncrNumber + '" />

Comment:  <textarea rows="4" class="form-control" id="comm' + IncrNumber + '"></textarea>
</code>```

Since these divs are being dynamically added with Javascript, I cannot use Razor and therefore cannot convert these text boxes into "HTML.TextBoxFor(x.start)..."

Since clicking a button will generate a variable, unlimited number of these fields, I cannot add them to my Model, anyways.

How can I get the values of startX, endX, and commX in my controller?

EDIT:

There exists a Many-To-One relationship between DBO.Televiewers[ID, Date] and DBO.Annotations[ID, TeleviewerID, Start, End, Comment].  The user can add as many Annotation objects as they want per Televiewer.

VIEW:

```<code><div class="panel panel-form-5">
<div class="panel-heading">
    <h3 class="panel-title">Edit Televiewer</h3>
</div>
<div class="panel-body">

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        @Html.Label("Hole Name")
        @Html.EditorFor(m => m.HoleName, new { htmlAttributes = new { @class = "form-control" } })
        <br />
        @Html.Label("Televiewer Date")
        @Html.EditorFor(m => m.TeleviewerDate, new { htmlAttributes = new { @class = "form-control" } })
        <br />
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-10">
                        <h4>Annotations</h4>
                    </div>
                    <div class="col-lg-2">
                        <div id="addbuttondiv">
                            <button onclick="addAnswer(); return false;" class="btn btn-default">Add New</button>
                        </div>

                    </div>
                </div>
                <hr />
                <div id="annotations">

                </div>
            </div>
        </div>
        <br />
                @Html.ActionLink("Back", "Index", "Televiewer", null, new { @class = "btn btn-default" })
                <input type="submit" value="Calculate & Save" class="btn btn-primary" />
       }

            </div>
        </div>
        <script>
            var answers = 0;

            function addAnswer() {
                var write = document.getElementById('annotations');
                write.innerHTML += ' <div class="row"><div class="col-lg-3 col-lg-offset-1">Start Depth: <input type="text" class="form-control" id="start' + answers + '"/></div><div class="col-lg-3 col-lg-offset-4" >End Depth: <input type="text" class="form-control" id="end' + answers + '" /></div></div><br /><div class="row"><div class="col-lg-1 col-lg-offset-2"><br />Comment:</div><div class="col-lg-6"><textarea rows="4" class="form-control" id="comm' + answers + '"></textarea></div></div><hr/>';
                answers++;
            }
        </script>
</code>```

答:
Taking an approach similar to this story:  MVC Form not able to post List of objects

Here are the basic models:

```<code>public class Televiewer
{

    public string HoleId { get; set; }

    public DateTime Date { get; set; }

    public List<Annotation> Annotations { get; set; }
}

public class Annotation
{
    public int AnnotationId { get; set; }
    public string HoleId { get; set; } //---- foreign key
    public int StartDepth { get; set; }
    public int EndDepth { get; set; }
    public string Comment { get; set; }
}
</code>```

In the html, for your 'Annotations" section:

```<code><div id="Annotations">
    @foreach (var ann in Model.Annotations)
    {
       <div class="annotation">
         <input type="text" class="form-control startDepth" name="Annotations[@i].StartDepth" value="@Model.Annotations[i].StartDepth" />
         <input type="text" class="form-control endDepth" name="Annotations[@i].EndDepth" value="@Model.Annotations[i].EndDepth" />
         <textarea rows="4" class="form-control comment"name="Annotations[@i].Comment" >@Model.Annotations[i].Comment</textarea>
       </div>
     }
</div>
</code>```

In the javascript, when you click the "Add" button:

```<code>function addAnswer()
{
    var index = $('#Annotations').find('.annotation').length;
    var html = '<br><div class="annotation">'
            + '<input type="text" class="form-control startDepth" name="Annotations[' + index + '].StartDepth" value="" />'
            + '<input type="text" class="form-control endDepth" name="Annotations[' + index + '].EndDepth" value="" />'
            + '<textarea rows="4" class="form-control comment"name="Annotations[' + index + '].Comment" ></textarea>'
            + '</div>';
    $('#Annotations').append(html);
}
</code>```

That should roughly plug in to your form submit.  You may have to iron out a few kinks (can't say what because I don't have enough of your code).

Notes:
1.  View models are your friend.  If you need to wrap up some data, make a model for it.
2.  Creating the html in the javascript the way I did is ok but using html templates would be better.  I just didn't want to open that can or worms here.
3.  The models I used are obviously stripped down.  I'm assuming you are using EF though so you'll have to adjust accordingly.

Body:
When the user clicks a button, the following HTML gets added to the page by Javascript, and the value of IncrNumber increases each time the button is clicked, so the first click would produce divs with the following ID's: (start0, end0, comm0) and the second click would produce ID's (start1, end1, comm1) and so on.

Start: <input type="text" class="form-control" id="start' + IncrNumber + '"/>

End: <input type="text" class="form-control" id="end' + IncrNumber + '" />

Comment:  <textarea rows="4" class="form-control" id="comm' + IncrNumber + '"></textarea>

Since these divs are being dynamically added with Javascript, I cannot use Razor and therefore cannot convert these text boxes into "HTML.TextBoxFor(x.start)..."

Since clicking a button will generate a variable, unlimited number of these fields, I cannot add them to my Model, anyways.

How can I get the values of startX, endX, and commX in my controller?

EDIT:

There exists a Many-To-One relationship between DBO.Televiewers[ID, Date] and DBO.Annotations[ID, TeleviewerID, Start, End, Comment].  The user can add as many Annotation objects as they want per Televiewer.

VIEW:

Edit Televiewer

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        @Html.Label("Hole Name")
        @Html.EditorFor(m => m.HoleName, new { htmlAttributes = new { @class = "form-control" } })

        @Html.Label("Televiewer Date")
        @Html.EditorFor(m => m.TeleviewerDate, new { htmlAttributes = new { @class = "form-control" } })

Annotations

                            <button onclick="addAnswer(); return false;" class="btn btn-default">Add New</button>

                @Html.ActionLink("Back", "Index", "Televiewer", null, new { @class = "btn btn-default" })
                <input type="submit" value="Calculate & Save" class="btn btn-primary" />
       }

Body:
Taking an approach similar to this story:  MVC Form not able to post List of objects

Here are the basic models:

public class Televiewer
{

    public string HoleId { get; set; }

    public DateTime Date { get; set; }

    public List<Annotation> Annotations { get; set; }
}

public class Annotation
{
    public int AnnotationId { get; set; }
    public string HoleId { get; set; } //---- foreign key
    public int StartDepth { get; set; }
    public int EndDepth { get; set; }
    public string Comment { get; set; }
}

In the html, for your 'Annotations" section:

<div id="Annotations">
    @foreach (var ann in Model.Annotations)
    {
       <div class="annotation">
         <input type="text" class="form-control startDepth" name="Annotations[@i].StartDepth" value="@Model.Annotations[i].StartDepth" />
         <input type="text" class="form-control endDepth" name="Annotations[@i].EndDepth" value="@Model.Annotations[i].EndDepth" />
         <textarea rows="4" class="form-control comment"name="Annotations[@i].Comment" >@Model.Annotations[i].Comment</textarea>
       </div>
     }
</div>

In the javascript, when you click the "Add" button:

function addAnswer()
{
    var index = $('#Annotations').find('.annotation').length;
    var html = '<br><div class="annotation">'
            + '<input type="text" class="form-control startDepth" name="Annotations[' + index + '].StartDepth" value="" />'
            + '<input type="text" class="form-control endDepth" name="Annotations[' + index + '].EndDepth" value="" />'
            + '<textarea rows="4" class="form-control comment"name="Annotations[' + index + '].Comment" ></textarea>'
            + '</div>';
    $('#Annotations').append(html);
}

That should roughly plug in to your form submit.  You may have to iron out a few kinks (can't say what because I don't have enough of your code).

Notes:
1.  View models are your friend.  If you need to wrap up some data, make a model for it.
2.  Creating the html in the javascript the way I did is ok but using html templates would be better.  I just didn't want to open that can or worms here.
3.  The models I used are obviously stripped down.  I'm assuming you are using EF though so you'll have to adjust accordingly.


问:
Error on overriding setter/getter of property
I'm having a strange error when trying to override the setter and getter of a property.

On my header file I've defined the following property:

```<code>@property (strong, nonatomic) NSDate *startedOn;
</code>```

On the implementation, I have this setter:

```<code>- (NSDate *)startedOn {
    if (!_startedOn) {
        [self updateStartedOn];
    }

    return _startedOn;
}
</code>```

Everything is working as it should at this point, but, when I try to override the setter like this:

```<code>- (void)setStartedOn:(NSDate *)startedOn {
    _startedOn = startedOn;
}
</code>```

I get the following error:

This doesn't make any sense to me, what I've checked:

The setter nor getter have any duplicated definition

The parent class doesn't have any duplicated definition

None of the class's categories have any duplicated definition

Does any one have a clue of what I'm doing wrong?
Thanks.

答:
Try to put in the implementation file;</p>

```<code>@synthesize startedOn = _startedOn;
</code>```

Body:
I'm having a strange error when trying to override the setter and getter of a property.

On my header file I've defined the following property:

@property (strong, nonatomic) NSDate *startedOn;

On the implementation, I have this setter:

- (NSDate *)startedOn {
    if (!_startedOn) {
        [self updateStartedOn];
    }

    return _startedOn;
}

Everything is working as it should at this point, but, when I try to override the setter like this:

- (void)setStartedOn:(NSDate *)startedOn {
    _startedOn = startedOn;
}

I get the following error:

This doesn't make any sense to me, what I've checked:

The setter nor getter have any duplicated definition

The parent class doesn't have any duplicated definition

None of the class's categories have any duplicated definition

Does any one have a clue of what I'm doing wrong?
Thanks.

Body:
Try to put in the implementation file;

@synthesize startedOn = _startedOn;


问:
R Creating a new variable name by partially matching other variable names
I would like to create a new variable x if there is an a or A in any of the other variable names with the following sample:

```<code>structure(list(A = 10L, a = 20L, abc = 1L), .Names = c("A", "a", "abc"),
class = "data.frame", row.names = c(NA, -1L))
</code>```

The result should look like this:

```<code>structure(list(A = 10L, a = 20L, abc = 1L, x = 31L), .Names = c("A", "a",
"abc", "x"), class = "data.frame", row.names = c(NA, -1L))
</code>```

I attempted to accomplish this via:

```<code>names1$x[grep("a" | "A", colnames(names1))]
</code>```

The following error resulted:

"Error in "a" | "A" : operations are possible only for numeric, logical or complex types"

I also tried to only match a but this resulted in NULL.

答:
We could use which and grepl to get the indices which match the "A|a" requirement.

In my code, I've added in an element b, just to show that b is not summed over. I've copied your code apart from that.

```<code>input <- structure(list(A = 10L, a = 20L, abc = 1L, b = 3L), .Names = c("A", "a", "abc", "b"), class = "data.frame", row.names = c(NA, -1L))

> input
   A  a abc b
1 10 20   1 3
</code>```

Then we can do:

```<code>input$x <- sum(input[which(grepl("a|A",names(input)))])

> input
   A  a abc b  x
1 10 20   1 3 31
</code>```

Note how b is not summed over.

Hope this is what you were after!

Body:
I would like to create a new variable x if there is an a or A in any of the other variable names with the following sample:

structure(list(A = 10L, a = 20L, abc = 1L), .Names = c("A", "a", "abc"),
class = "data.frame", row.names = c(NA, -1L))

The result should look like this:

structure(list(A = 10L, a = 20L, abc = 1L, x = 31L), .Names = c("A", "a",
"abc", "x"), class = "data.frame", row.names = c(NA, -1L))

I attempted to accomplish this via:

names1$x[grep("a" | "A", colnames(names1))]

The following error resulted:

"Error in "a" | "A" : operations are possible only for numeric, logical or complex types"

I also tried to only match a but this resulted in NULL.

Body:
We could use which and grepl to get the indices which match the "A|a" requirement.

In my code, I've added in an element b, just to show that b is not summed over. I've copied your code apart from that.

input <- structure(list(A = 10L, a = 20L, abc = 1L, b = 3L), .Names = c("A", "a", "abc", "b"), class = "data.frame", row.names = c(NA, -1L))

> input
   A  a abc b
1 10 20   1 3

Then we can do:

input$x <- sum(input[which(grepl("a|A",names(input)))])

> input
   A  a abc b  x
1 10 20   1 3 31

Note how b is not summed over.

Hope this is what you were after!


问:
Prevent Jenkins to rebuild the entire project everytime
Sometimes I have to start my Jenkins manually (when I add some new plugins for example) to make sure it works properly. Normally, a build is setup to run at midnight.

In order to work faster, I would like to know, if I could start a build with Jenkins, without having to go through the whole process : pull from git, clear from database, composer update etc...

Because I am only adding features to Jenkins, and not the source code itself.

I use ant to build my project.

答:
Depending on the job type you build, you should be able to specify a certain directory in the file system as workspace location. Then you can just do a rebuild of you program. Depending on your make tool this should just rebuild files changed this the last build, e.g. do to the git pull.

See e.g. https://ingorichter.blogspot.de/2012/02/jenkins-change-workspaces-and-build.html and Custom workspace in jenkins


问:
Show camera2 preview in wallpaperservice
I need to show camera preview in live wallpaper.
I've already made for android < M versions. But can't understand how it working with new API. Oldest Camera is deprecated now

In google example they put it in xml and in TextureView but how I can change that for my needs, I can't understand.

Anyway Thanks!

Google example
https://github.com/googlesamples/android-Camera2Basic

Below my code.

Start wallpaper

```<code>Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, TransparentWallpaperService.class));
startActivity(intent);
</code>```

TransparentWallpaperService

```<code>public class TransparentWallpaperService extends WallpaperService {

@Override
public Engine onCreateEngine() {
    return new GlowEngine();
}

private class GlowEngine extends Engine {

    private final Handler handler = new Handler();

    private final Runnable viewRunner = new Runnable() {

        @Override
        public void run() {

            drawView();

        }

    };

    private boolean visible = true;
    private CameraView view;

    public GlowEngine() {
        super();
        view = new CameraView(getBaseContext(), getSurfaceHolder());
        handler.post(viewRunner);
    }

    @Override
    public void onVisibilityChanged(boolean visible) {
        this.visible = visible;
        if (visible) {
            handler.post(viewRunner);
        }
        else {
            handler.removeCallbacks(viewRunner);
        }
    }

    @Override
    public void onSurfaceDestroyed(SurfaceHolder holder) {
        super.onSurfaceDestroyed(holder);
        this.visible = false;
        handler.removeCallbacks(viewRunner);
    }

    private void drawView() {
        view.surfaceChanged(getSurfaceHolder(), OPAQUE, view.getWidth(), view.getHeight());
        handler.removeCallbacks(viewRunner);
        if (visible) {
            handler.postDelayed(viewRunner, 4000);
        }
    }
}
}
</code>```

CameraView class

```<code>public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder holder;

private Camera camera;

public CameraView(Context context) {

    super(context);

    camera = getCameraInstance();

}

public CameraView(Context context, SurfaceHolder holder) {

    this(context);
    this.holder = holder;

    holder.addCallback(this);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {

    if(camera == null) {
        camera = getCameraInstance();
    }

    if(camera != null) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        }
        catch (IOException e) {
            Log.e("CameraView", "Error setting camera preview: " + e.getMessage());
        }
    }

}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {

    boolean portrait = true;

    if (width > 0 && height >0 && width < height){
        portrait =true;
    } else if (width > 0 && height >0 && width > height){
        portrait = false;
    }

    Camera.Parameters parameters;
    if (camera == null) {
        camera = getCameraInstance();
    }
    if (camera != null){
        parameters = camera.getParameters();
        Camera.Size size = parameters.getPictureSize();
        size = parameters.getPreviewSize();
        parameters.setPreviewSize(size.width, size.height);
        if (portrait) {
            camera.setDisplayOrientation(90);
        } else {
            camera.setDisplayOrientation(180);
        }
        try {
            camera.setParameters(parameters);
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    if(camera != null) {
        try {
            camera.stopPreview();
            camera.release();
        }
        catch (Exception e) {
            Log.e("CameraView", "Error stopping camera preview: " + e.getMessage());
        }
    }

}

private Camera getCameraInstance() {

    Context context = getContext();
    Camera camera = null;
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        try {
            camera = Camera.open();
        }
        catch (Exception e) {
            Log.e("CameraView", "Error getting camera instance: " + e.getMessage());
        }
    }
    else {
        Log.i("CameraView", "No camera found!");
    }
    return camera;
}
}
</code>```

答:
You can just keep using the old API; it's fully functional even on new devices.

Otherwise, you can just replace the TextureView with a SurfaceView easily enough; instead of creating a Surface from TextureView's SurfaceTexture, get a Surface from SurfaceView's SurfaceHolder in surfaceChanged.

Body:
I need to show camera preview in live wallpaper.
I've already made for android < M versions. But can't understand how it working with new API. Oldest Camera is deprecated now

In google example they put it in xml and in TextureView but how I can change that for my needs, I can't understand.

Anyway Thanks!

Google example
https://github.com/googlesamples/android-Camera2Basic

Below my code.

Start wallpaper

Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, TransparentWallpaperService.class));
startActivity(intent);

TransparentWallpaperService

public class TransparentWallpaperService extends WallpaperService {

@Override
public Engine onCreateEngine() {
    return new GlowEngine();
}

private class GlowEngine extends Engine {

    private final Handler handler = new Handler();

    private final Runnable viewRunner = new Runnable() {

        @Override
        public void run() {

            drawView();

        }

    };

    private boolean visible = true;
    private CameraView view;

    public GlowEngine() {
        super();
        view = new CameraView(getBaseContext(), getSurfaceHolder());
        handler.post(viewRunner);
    }

    @Override
    public void onVisibilityChanged(boolean visible) {
        this.visible = visible;
        if (visible) {
            handler.post(viewRunner);
        }
        else {
            handler.removeCallbacks(viewRunner);
        }
    }

    @Override
    public void onSurfaceDestroyed(SurfaceHolder holder) {
        super.onSurfaceDestroyed(holder);
        this.visible = false;
        handler.removeCallbacks(viewRunner);
    }

    private void drawView() {
        view.surfaceChanged(getSurfaceHolder(), OPAQUE, view.getWidth(), view.getHeight());
        handler.removeCallbacks(viewRunner);
        if (visible) {
            handler.postDelayed(viewRunner, 4000);
        }
    }
}
}

CameraView class

public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder holder;

private Camera camera;

public CameraView(Context context) {

    super(context);

    camera = getCameraInstance();

}

public CameraView(Context context, SurfaceHolder holder) {

    this(context);
    this.holder = holder;

    holder.addCallback(this);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {

    if(camera == null) {
        camera = getCameraInstance();
    }

    if(camera != null) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        }
        catch (IOException e) {
            Log.e("CameraView", "Error setting camera preview: " + e.getMessage());
        }
    }

}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {

    boolean portrait = true;

    if (width > 0 && height >0 && width < height){
        portrait =true;
    } else if (width > 0 && height >0 && width > height){
        portrait = false;
    }

    Camera.Parameters parameters;
    if (camera == null) {
        camera = getCameraInstance();
    }
    if (camera != null){
        parameters = camera.getParameters();
        Camera.Size size = parameters.getPictureSize();
        size = parameters.getPreviewSize();
        parameters.setPreviewSize(size.width, size.height);
        if (portrait) {
            camera.setDisplayOrientation(90);
        } else {
            camera.setDisplayOrientation(180);
        }
        try {
            camera.setParameters(parameters);
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    if(camera != null) {
        try {
            camera.stopPreview();
            camera.release();
        }
        catch (Exception e) {
            Log.e("CameraView", "Error stopping camera preview: " + e.getMessage());
        }
    }

}

private Camera getCameraInstance() {

    Context context = getContext();
    Camera camera = null;
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        try {
            camera = Camera.open();
        }
        catch (Exception e) {
            Log.e("CameraView", "Error getting camera instance: " + e.getMessage());
        }
    }
    else {
        Log.i("CameraView", "No camera found!");
    }
    return camera;
}
}


问:
Excel Return Date before another date by another column name
I have two sheets of data with the following.

I want return the date from sheet 2 on sheet 1 with the start date BEFORE the remove date.  For example.  For Customer A, the remove date is 12/29/2016.  I would want to return the date of 12/20/2014 from sheet 2 as it is the next previous date from the remove date of 12/29/2016 from sheet 1 and is removed prior to the third date of 1/20/2017.  Similarly for Customer B, the date returned would be 11/9/2013.

Vlookup will not work as there are more than one unique value for customer and I had no luck with index and match.  Is there any other possible solution?

Here is an edit.  The Sumproduct and aggregate method for the start date works great.  The issue is I need the last date to be the first record after the replacement date.  So in this case, it would be 2/1/16.  Using the Min or Max sumproduct and aggregate method, I get either 0 or the max date of 3/22/17, which is not what I want.

答:
Since dates are (for all intents and purposes) numbers, this is really nothing more than a pseudo-MAXIFS question. Try,</p>

```<code>=aggregate(14, 6, (b2:b7)/((a2:a7="A")*(b2:B7<date(2016, 12, 29))), 1)
</code>```

Body:
Since dates are (for all intents and purposes) numbers, this is really nothing more than a pseudo-MAXIFS question. Try,

=aggregate(14, 6, (b2:b7)/((a2:a7="A")*(b2:B7<date(2016, 12, 29))), 1)


问:
MySQL query to check a row's cells for value and return column name
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

```<code>-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';
</code>```

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

答:
Use CONCAT_WS() to concatenate all the column names where the value is yes. NULL doesn't get included by CONCAT_WS(), so returning that for the no columns will leave them out of the result.

```<code>SELECT CONCAT_WS(',', IF(Banana = 'yes', 'Banana', NULL),
                      IF(Apple = 'yes', 'Apple', NULL),
                      IF(Pear = 'yes', 'Pear', NULL),
                      ...) AS fruits
FROM yourTable
WHERE property = 'fruit';
</code>```

Body:
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

Body:
Use CONCAT_WS() to concatenate all the column names where the value is yes. NULL doesn't get included by CONCAT_WS(), so returning that for the no columns will leave them out of the result.

SELECT CONCAT_WS(',', IF(Banana = 'yes', 'Banana', NULL),
                      IF(Apple = 'yes', 'Apple', NULL),
                      IF(Pear = 'yes', 'Pear', NULL),
                      ...) AS fruits
FROM yourTable
WHERE property = 'fruit';


问:
Xcode: How do I output a variable length array to the output window?
I have a user interface that takes some parameters. Then, the user clicks the calculate button. At the end of that calculation, I write to a variable called roots. It will hold some number of Double values. I need to show these values on the same window where the user put in their parameters. How can I achieve this? New to Swift/Xcode/Mac in general.

The minimum I need to achieve is to just show the values of the array on that window. If I can make it pretty, that's a bonus.

答:
put a label (myLabel) in that view, connect it to your UIViewController of the case as an outlet, then in the action of the button:</p>

```<code>myLabel.text = roots.description
</code>```

Body:
put a label (myLabel) in that view, connect it to your UIViewController of the case as an outlet, then in the action of the button:

myLabel.text = roots.description