问:
Desktop Bridge UWP Windows.Services.Store;
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

```<code>Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.
</code>```

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

```<code><TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />
</code>```

Anyone know how to get around it?

答: Visual Studio update 15.5 includes an update to the desktop bridge packaging project that allows you to include UWP Api's.</p>

Body:
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

<TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />

Anyone know how to get around it?


来源: stackexchange

问:
Zebra Printer C# code to print barcode label
This is my *.prn file:

```
I8,A,001 Q0001,0
q831
rN
S5
D10
ZT
JF
O
R20,0
f100
N
B775,188,2,1,2,6,160,B,"SM00020000"
X0,199,1,0,200
P1
```

SM00020000 being the barcode.

```<code>string s = "I8,A,001\n\n\nQ0001,0\nq831\nrN\nS5\nD10\nZT\nJF\nO\nR20,0\nf100\nN\nB775,188,2,1,2,6,160,B,\"SM00020000\",199,1,0,200\nP1\n";

PrintDialog pd = new new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.
pd.PrinterSettings.PrinterName = "ZDesigner GT800 (EPL)";
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);

public static bool SendStringToPrinter(string szPrinterName, string szString)
{
    IntPtr pBytes;
    Int32 dwCount;
    // How many characters are in the string?
    dwCount = szString.Length;
    // Assume that the printer is expecting ANSI text, and then convert
    // the string to ANSI text.
    pBytes = Marshal.StringToCoTaskMemAnsi(szString);
    // Send the converted ANSI string to the printer.
    SendBytesToPrinter(szPrinterName, pBytes, dwCount);
    Marshal.FreeCoTaskMem(pBytes);
    return true;
}

public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
    Int32 dwError = 0, dwWritten = 0;
    IntPtr hPrinter = new IntPtr(0);
    DOCINFOA di = new DOCINFOA();
    bool bSuccess = false; // Assume failure unless you specifically succeed.

    di.pDocName = "My C#.NET RAW Document";
    di.pDataType = "RAW";

    // Open the printer.
    if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
    {
        // Start a document.
        if (StartDocPrinter(hPrinter, 1, di))
        {
            // Start a page.
            if (StartPagePrinter(hPrinter))
            {
                // Write your bytes.
                bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                EndPagePrinter(hPrinter);

            }
            EndDocPrinter(hPrinter);
        }
        ClosePrinter(hPrinter);
    }
    // If you did not succeed, GetLastError may give more information
    // about why not.
    if (bSuccess == false)
    {
        dwError = Marshal.GetLastWin32Error();
    }
    return bSuccess;
}
</code>```

This code is not helping me print my label. The document goes to the print queue but nothing happens after that. Although the printer is correctly configured and I have successfully printed with Zebra Designer.

Also I'd like the above code such that it prints 3 labels in one row, since I have the media which has 3 stickers in one row. How can that be achieved?

My printer model is ZDesigner GT800 (EPL).

答:
If any of these does not work, you can write your zpl commands into a file using c# and directly copy it to the printer, if it is shared in network. </p>

```<code>    public void Print(int numCopies = 1)
    {

        int randomInt = (new Random()).Next(1000); //this random value is intented to get the collision change of prn file names reduced
        string SERVERPATH = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/PrintOperations/"));

        if (!Directory.Exists(SERVERPATH))
        {
            Directory.CreateDirectory(SERVERPATH);

        }
        String prnFilePath = SERVERPATH + MethodName + randomInt + ".prn";
        String fullPrinterPath = @"\\"+ServerName+@"\"+ printerName;
        var createdFile = System.IO.File.Create(prnFilePath);
        createdFile.Close();
        System.IO.File.WriteAllText(prnFilePath, parsedZpl);
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = string.Format("/C Copy \"{0}\" \"{1}\"", prnFilePath ,fullPrinterPath);
        process.StartInfo = startInfo;
        for (int i =0; i< numCopies; i++)
        {
            process.Start();
            process.WaitForExit();

        }

        System.IO.File.Delete(prnFilePath);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my *.prn file:

I8,A,001 Q0001,0
q831
rN
S5
D10
ZT
JF
O
R20,0
f100
N
B775,188,2,1,2,6,160,B,"SM00020000"
X0,199,1,0,200
P1

SM00020000 being the barcode.

string s = "I8,A,001\n\n\nQ0001,0\nq831\nrN\nS5\nD10\nZT\nJF\nO\nR20,0\nf100\nN\nB775,188,2,1,2,6,160,B,\"SM00020000\",199,1,0,200\nP1\n";

PrintDialog pd = new new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.
pd.PrinterSettings.PrinterName = "ZDesigner GT800 (EPL)";
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);

public static bool SendStringToPrinter(string szPrinterName, string szString)
{
    IntPtr pBytes;
    Int32 dwCount;
    // How many characters are in the string?
    dwCount = szString.Length;
    // Assume that the printer is expecting ANSI text, and then convert
    // the string to ANSI text.
    pBytes = Marshal.StringToCoTaskMemAnsi(szString);
    // Send the converted ANSI string to the printer.
    SendBytesToPrinter(szPrinterName, pBytes, dwCount);
    Marshal.FreeCoTaskMem(pBytes);
    return true;
}

public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
    Int32 dwError = 0, dwWritten = 0;
    IntPtr hPrinter = new IntPtr(0);
    DOCINFOA di = new DOCINFOA();
    bool bSuccess = false; // Assume failure unless you specifically succeed.

    di.pDocName = "My C#.NET RAW Document";
    di.pDataType = "RAW";

    // Open the printer.
    if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
    {
        // Start a document.
        if (StartDocPrinter(hPrinter, 1, di))
        {
            // Start a page.
            if (StartPagePrinter(hPrinter))
            {
                // Write your bytes.
                bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                EndPagePrinter(hPrinter);

            }
            EndDocPrinter(hPrinter);
        }
        ClosePrinter(hPrinter);
    }
    // If you did not succeed, GetLastError may give more information
    // about why not.
    if (bSuccess == false)
    {
        dwError = Marshal.GetLastWin32Error();
    }
    return bSuccess;
}

This code is not helping me print my label. The document goes to the print queue but nothing happens after that. Although the printer is correctly configured and I have successfully printed with Zebra Designer.

Also I'd like the above code such that it prints 3 labels in one row, since I have the media which has 3 stickers in one row. How can that be achieved?

My printer model is ZDesigner GT800 (EPL).

Body:
If any of these does not work, you can write your zpl commands into a file using c# and directly copy it to the printer, if it is shared in network.

    public void Print(int numCopies = 1)
    {

        int randomInt = (new Random()).Next(1000); //this random value is intented to get the collision change of prn file names reduced
        string SERVERPATH = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/PrintOperations/"));

        if (!Directory.Exists(SERVERPATH))
        {
            Directory.CreateDirectory(SERVERPATH);

        }
        String prnFilePath = SERVERPATH + MethodName + randomInt + ".prn";
        String fullPrinterPath = @"\\"+ServerName+@"\"+ printerName;
        var createdFile = System.IO.File.Create(prnFilePath);
        createdFile.Close();
        System.IO.File.WriteAllText(prnFilePath, parsedZpl);
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = string.Format("/C Copy \"{0}\" \"{1}\"", prnFilePath ,fullPrinterPath);
        process.StartInfo = startInfo;
        for (int i =0; i< numCopies; i++)
        {
            process.Start();
            process.WaitForExit();

        }

        System.IO.File.Delete(prnFilePath);
}


问:
Django Image Grid Gallery
I am trying to setup a grid gallery in my Django website similar to pinterest.com.

I have the following HTML code:

```<code><div class="row text-center text-lg-left">
    <div class="col-lg-3 col-md-4 col-xs-6">
      <a href="#" class="d-block mb-4 h-100">
        {% for img in imgs %}
        <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
        {% endfor %}
      </a>
    </div>
  </div>
</code>```

Here is my views.py

```<code>def gallery(request):
    path = "C:/Users/fela/Pictures/"
    img_list = os.listdir(path)
    return render(request, 'gallery.html', {'imgs': img_list})
</code>```

The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png).

The expected result should be similar to pinterest, it should be next to each other to fill up the screen.

I have tried using bootstrap 4 and bootstrap 3 with same results.

答:
I was able to figure it out using another method. Here is the code in case it helps someone else.</p>

```<code> <div style="width:100%">
  {% for img in imgs %}
      <div style="float:left; width:200px; height:200px;">
          <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
      </div>
  {% endfor%}
  </div>
</code>```

Title: Django Image Grid Gallery

Body:
I am trying to setup a grid gallery in my Django website similar to pinterest.com.

I have the following HTML code:

        {% for img in imgs %}

        {% endfor %}

Here is my views.py

def gallery(request):
    path = "C:/Users/fela/Pictures/"
    img_list = os.listdir(path)
    return render(request, 'gallery.html', {'imgs': img_list})

The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png).

The expected result should be similar to pinterest, it should be next to each other to fill up the screen.

I have tried using bootstrap 4 and bootstrap 3 with same results.

Body:
I was able to figure it out using another method. Here is the code in case it helps someone else.

 <div style="width:100%">
  {% for img in imgs %}
      <div style="float:left; width:200px; height:200px;">
          <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
      </div>
  {% endfor%}
  </div>


问:
I want to create a matlab program that stores and increment the value inside the array after certain events
```<code>for i=1:2

    dice_roll_1=randi(6);
    dice_roll_2=randi(6);
    player_dice_roll=dice_roll_1+dice_roll_2;
    player_position=player_dice_roll;

end
</code>```

For the second round I want the array player_position to have its elements added by the new values of dice_roll_1 and dice_roll_2.

答:
here's a version without for loops:

```<code>% this makes 10 rolls of two dice, but change 10 to whatever # you want
dice_rolls= randi(6,2,10);
</code>```

then

```<code>sum(dice_rolls) % is the sum of each pair
</code>```

and

```<code>cumsum(sum(dice_rolls))
</code>```

is the cumulative sum of rolls in each round...

For example:

```<code>dice_rolls= randi(6,2,3)
</code>```

dice_rolls =

```<code> 5     4     6
 2     5     6
</code>```

these are the 3 rolls of 2 dice (lucky 6 6 at the last roll)

Then >>

```<code>cumsum(sum(dice_rolls))
</code>```

ans =

```<code> 7    16    28
</code>```

you can see the answer is: (roll 1), (roll 1 + roll 2), (roll 1 + roll 2 + roll 3)

that's what you wanted right?

Body:
for i=1:2

    dice_roll_1=randi(6);
    dice_roll_2=randi(6);
    player_dice_roll=dice_roll_1+dice_roll_2;
    player_position=player_dice_roll;

end

For the second round I want the array player_position to have its elements added by the new values of dice_roll_1 and dice_roll_2.

Body:
here's a version without for loops:

% this makes 10 rolls of two dice, but change 10 to whatever # you want
dice_rolls= randi(6,2,10);

then

sum(dice_rolls) % is the sum of each pair

and

cumsum(sum(dice_rolls))

is the cumulative sum of rolls in each round...

For example:

dice_rolls= randi(6,2,3)

dice_rolls =

 5     4     6
 2     5     6

these are the 3 rolls of 2 dice (lucky 6 6 at the last roll)

Then >>

cumsum(sum(dice_rolls))

ans =

 7    16    28

you can see the answer is: (roll 1), (roll 1 + roll 2), (roll 1 + roll 2 + roll 3)

that's what you wanted right?


问:
Redux reducer state is undefined at production
I have react-redux app which works fine without error during development, but in production, It doesn't work.

I've completely removed redux-dev-tolls etc but no chance.

I'm getting this error;

```<code>TypeError: Cannot read property 'isLoading' of undefined
</code>```

I declared signInStatus, and isLoading  inside of react render function like this;

```<code>const {signin, signInStatus} = this.props
const {
    isLoading,
    isSucceeded,
    idErrorMessage,
    passwordErrorMessage,
    generalErrorMessage
} = signInStatus;
</code>```

Connection;

```<code>const reduxInjected = connect(({signInStatus}) => ({signInStatus}), {
    signin,
    signInResetForm,
    signinStorage
})(LoginEmailPasswordForm);
....
</code>```

Reducer;

```<code>const signInStatus = (state = {isLoading: false, isSucceeded: false}, action) => {
    switch (action.type) {
        // Hot Module Replacement
        case EPIC_END:
            return {isLoading: false, isSucceeded: false};

        case ...:
            return {...state, isLoading: false, isSucceeded: false};

        case ...:
        case ...:
        case ...:
            return {isLoading: true, isSucceeded: false};

        case ...:
        case ...:
            const {accessToken, idToken, expiresIn} = action;
            let expiresAt = JSON.stringify((action.expiresIn * 1000) + new Date().getTime());
            return {isSucceeded: true, token: {accessToken, idToken, expiresAt}};

        case ...:
            return {isSucceeded: true, isLoggedIn: true, token: action.token, user: action.user};

        case ...:
            return {}

        case ...:
            const newState = {}
            const {error} = action;
            ...
            return {...newState, isLoading: false, isSucceeded: false};

        case ...:
            return {...state, isLoggedIn: true, user: action}

        case ...:
            return {}

        default:
            return {...state}
    }
}
</code>```

You can see signInStatus has initial state, but it says it's undefined

What could be the reason?

Thank you.

答:
It was about UglifyJsPlugin</p>

```<code>plugins: [
    // Don't Minify JS, redux doesn't like it
    // new UglifyJsPlugin({
    //     sourceMap: true,
    //     compress: false,
    // }),
],
</code>```

Body:
I have react-redux app which works fine without error during development, but in production, It doesn't work.

I've completely removed redux-dev-tolls etc but no chance.

I'm getting this error;

TypeError: Cannot read property 'isLoading' of undefined

I declared signInStatus, and isLoading  inside of react render function like this;

const {signin, signInStatus} = this.props
const {
    isLoading,
    isSucceeded,
    idErrorMessage,
    passwordErrorMessage,
    generalErrorMessage
} = signInStatus;

Connection;

const reduxInjected = connect(({signInStatus}) => ({signInStatus}), {
    signin,
    signInResetForm,
    signinStorage
})(LoginEmailPasswordForm);
....

Reducer;

const signInStatus = (state = {isLoading: false, isSucceeded: false}, action) => {
    switch (action.type) {
        // Hot Module Replacement
        case EPIC_END:
            return {isLoading: false, isSucceeded: false};

        case ...:
            return {...state, isLoading: false, isSucceeded: false};

        case ...:
        case ...:
        case ...:
            return {isLoading: true, isSucceeded: false};

        case ...:
        case ...:
            const {accessToken, idToken, expiresIn} = action;
            let expiresAt = JSON.stringify((action.expiresIn * 1000) + new Date().getTime());
            return {isSucceeded: true, token: {accessToken, idToken, expiresAt}};

        case ...:
            return {isSucceeded: true, isLoggedIn: true, token: action.token, user: action.user};

        case ...:
            return {}

        case ...:
            const newState = {}
            const {error} = action;
            ...
            return {...newState, isLoading: false, isSucceeded: false};

        case ...:
            return {...state, isLoggedIn: true, user: action}

        case ...:
            return {}

        default:
            return {...state}
    }
}

You can see signInStatus has initial state, but it says it's undefined

What could be the reason?

Thank you.

Body:
It was about UglifyJsPlugin

plugins: [
    // Don't Minify JS, redux doesn't like it
    // new UglifyJsPlugin({
    //     sourceMap: true,
    //     compress: false,
    // }),
],


问:
Conditional IF statement for mixed range of inputs (not in chronological order)
My situation is this: I'm trying to create a conditional IF statement that tests whether a cell falls within a mixed range of data and outputs a specific result. To be more specific, I want to search a range of serial numbers that correlate to a specific model year, however the serial numbers are not in numerical order (i.e. SN's 202-235, 241, 247-255 are model year 2015, and SN's 257, 201, 259-269 are model year 2016). Is there a way to create this?</p>

答:
This can be solved using a similar solution to the one here.

I've modified the formula to match your example

```<code>=INDEX({"",2016,2015,"",2015,"",2015,"",2016,"",2016,""},LARGE(IF([INPUT_VALUE]>{0,200,201,235,240,241,246,255,256,257,258,269},{1,2,3,4,5,6,7,8,9,10,11,12}),1))
</code>```

Replace [INPUT_VALUE] with the appropriate cell reference and make sure to press Ctrl+Shift+Enter as this is an array formula.

This solution works by finding the largest number that the input is greater than in the second array, and then cross referencing the first array. The third array is being used as a counter for this cross referencing.

This may not be the most intuitive solution, but I believe it is the most flexible as it evaluates the number directly and can deal with numbers not explicitly specified.

Body:
This can be solved using a similar solution to the one here.

I've modified the formula to match your example

=INDEX({"",2016,2015,"",2015,"",2015,"",2016,"",2016,""},LARGE(IF([INPUT_VALUE]>{0,200,201,235,240,241,246,255,256,257,258,269},{1,2,3,4,5,6,7,8,9,10,11,12}),1))

Replace [INPUT_VALUE] with the appropriate cell reference and make sure to press Ctrl+Shift+Enter as this is an array formula.

This solution works by finding the largest number that the input is greater than in the second array, and then cross referencing the first array. The third array is being used as a counter for this cross referencing.

This may not be the most intuitive solution, but I believe it is the most flexible as it evaluates the number directly and can deal with numbers not explicitly specified.


问:
Python- Remove all words that contain other words in a list
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

```<code> for line in wordlist:
        if line.find(...) --
</code>```

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

答:
I find jkerian's asnwer to be the best (assuming only one list) and I would like to explain why.

Here is my version of the code (as a function):

```<code>wordlist = ["a","arc","arcane","apple","car","carpenter","cat","zebra"];

def root_words(wordlist):
    result = []
    base = wordlist[0]
    for word in wordlist:
        if not word.startswith(base):
            result.append(base)
            base=word
    result.append(base)
    return result;

print root_words(wordlist);
</code>```

As long as the word list is sorted (you could do this in the function if you wanted to), this will get the result in a single parse. This is because when you sort the list, all words made up of another word in the list, will be directly after that root word. e.g. anything that falls between "arc" and "arcane" in your particular list, will also be eliminated because of the root word "arc".

ContentLicense: CC BY-SA 2.5

Body:
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

 for line in wordlist:
        if line.find(...) --

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

Body:
I find jkerian's asnwer to be the best (assuming only one list) and I would like to explain why.

Here is my version of the code (as a function):

wordlist = ["a","arc","arcane","apple","car","carpenter","cat","zebra"];

def root_words(wordlist):
    result = []
    base = wordlist[0]
    for word in wordlist:
        if not word.startswith(base):
            result.append(base)
            base=word
    result.append(base)
    return result;

print root_words(wordlist);

As long as the word list is sorted (you could do this in the function if you wanted to), this will get the result in a single parse. This is because when you sort the list, all words made up of another word in the list, will be directly after that root word. e.g. anything that falls between "arc" and "arcane" in your particular list, will also be eliminated because of the root word "arc".


问:
i need to get Last child of my firebase databse
i want to get last child  from my firebase data structure  in which i only know the reference of received and first child of it

i try this one but it will  return all child but i need only last one that use in query limiTolast(1) like this

```<code>  DatabaseReference users = mDatabase.child("received");
      //  DatabaseReference receiver = users.child(firebaseUser.getUid());
        final DatabaseReference receiver =
    users.child("GTjrWgpKjoeXUt4JdBJTYP1JkVT2");

        receiver.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                Log.d(TAG, "key count=" + postSnapshot.getKey());

                for (DataSnapshot sender: postSnapshot.getChildren()) {

                    Log.d(TAG, "sender key count=" + sender.getKey());

                }

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("SHAN " ,databaseError.getMessage());
        }
    });
</code>```

答:
It is a best solution to find the last exit child from firebase

```<code> String LASTMESSAGE=NULL; DatabaseReference dbref =
 Firebase.getInstance().getReference(); Query lastchield =
 FirebaseDatabase.child("yourchieldfororder")
                           .orderByKey().limitToLast(1); lastchield.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot ds) {
          LASTMESSAGE= ds.child("message").getValue().toString();
     }
     @Override
     public void onCancelled(DatabaseError databaseError) {
         LASTMESSAGE = "No-Last-MESSAGE-EXIT";
     } });`
</code>```

Query first order the child id then give you the last id of the child in data- snapshot.

Happy Coding!

Body:
i want to get last child  from my firebase data structure  in which i only know the reference of received and first child of it

i try this one but it will  return all child but i need only last one that use in query limiTolast(1) like this

  DatabaseReference users = mDatabase.child("received");
      //  DatabaseReference receiver = users.child(firebaseUser.getUid());
        final DatabaseReference receiver =
    users.child("GTjrWgpKjoeXUt4JdBJTYP1JkVT2");

        receiver.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                Log.d(TAG, "key count=" + postSnapshot.getKey());

                for (DataSnapshot sender: postSnapshot.getChildren()) {

                    Log.d(TAG, "sender key count=" + sender.getKey());

                }

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("SHAN " ,databaseError.getMessage());
        }
    });

Body:
It is a best solution to find the last exit child from firebase

 String LASTMESSAGE=NULL; DatabaseReference dbref =
 Firebase.getInstance().getReference(); Query lastchield =
 FirebaseDatabase.child("yourchieldfororder")
                           .orderByKey().limitToLast(1); lastchield.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot ds) {
          LASTMESSAGE= ds.child("message").getValue().toString();
     }
     @Override
     public void onCancelled(DatabaseError databaseError) {
         LASTMESSAGE = "No-Last-MESSAGE-EXIT";
     } });`

Query first order the child id then give you the last id of the child in data- snapshot.

Happy Coding!

ContentLicense: CC BY-SA 4.0


问:
View PDF or MS Office documents inside an iframe
I am trying to display different kinds of files inside a iframe. It works for text, images and pdf files but not working with MS office or Open office documents. Is there a way to do this? Also, it automatically starts to download files that cannot be opened, is there a way to stop this automatic download from happening?</p>

答:
Microsoft now provides a nice web viewer, explained here

It only works on files that are publicly available at some http endpoint, but thankfully, they do let you stick it an the iframe. Just append your filename as the src of this link:

view.officeapps.live.com/op/view.aspx?src=

A more interesting solution to me is to look around for ways to use open office on the command line. It has a capability to convert microsoft documents into open office format, at which point you can use the open source http://viewerjs.org/ and host it yourself if that's your style.


问:
How to index a 1D numpy array as if it is a matrix with 1 row?
I have a 1D numpy array like:

```<code>a = np.array([1,2,3,4,5])
</code>```

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

```<code>a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array
</code>```

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

答:
Also, you can use these as well:

```<code>In [7]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [8]: a = a[np.newaxis, :]

In [9]: a[0,2]
Out[9]: 3

# another approach using `None`
In [10]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [11]: a = a[None, :]

In [12]: a[0, 2]
Out[12]: 3
</code>```

When you use np.newaxis or None once, a new axis is added; Note that you've assign this to your original array to make modification to the final array.

Body:
I have a 1D numpy array like:

a = np.array([1,2,3,4,5])

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

Body:
Also, you can use these as well:

In [7]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [8]: a = a[np.newaxis, :]

In [9]: a[0,2]
Out[9]: 3

# another approach using `None`
In [10]: a = np.array([1,2,3,4,5])

# make it as row vector of shape (1, 5)
In [11]: a = a[None, :]

In [12]: a[0, 2]
Out[12]: 3

When you use np.newaxis or None once, a new axis is added; Note that you've assign this to your original array to make modification to the final array.


问:
Excel VBA - Autofill a Column according to InputBox
Current Outcome

```<code>A1     B1
Item   Deposit to
Apple  Trash
Banana
Grape
</code>```

```<code>Private Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Enter Where", "Deposit to", Trash)
Range("B2").Value = myValue
End Sub
</code>```

Trying to get the Value from the Input to auto-fill for the entire Column B as long as there is a value in Column A.

Attempted to place this with the Command Button, but can't seem to get it to work.

```<code>Sub test()
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
End Sub
</code>```

Desired outcome

```<code>A1     B1
Item   Deposit to
Apple  Trash
Banana Trash
Grape  Trash
</code>```

Is there a way to Prompt for value without the CommandButton?

At the moment, the CommandButton Works for the InputBox, but when i attempt the code to autofill it removes the Input and leaves blank.

答:
You can use InputBox() anywhere in code, generally, to prompt for input. You can separate that from your Command Button code.

For the first part, you can use this formula.  Where there's a value in column A, put the input in column B:

```<code>Sub t()
Dim myValue As String
Dim lastCel As Range

Set lastCel = Range("A" & Rows.Count).End(xlUp)
myValue = InputBox("Enter Where", "Deposit to")

Range("B2:B" & lastCel.Row).Formula = "=IF($A2<>""""," & """" & myValue & """" & ","""")"
Range("B2:B" & lastCel.Row).Value = Range("B2:B" & lastCel.Row).Value

Range("B2").Value = myValue
End Sub
</code>```

Edit:
The .Formula line is doing just as it reads - it's adding a formula to the range.

If you're in the worksheet, and in cell B2 enter the formula =IF($A2<>"","Bruce","") it will check if cell A2 is Empty.  If it's not empty, it will return Bruce.  If A2 is empty, will return an empty string "" (which in practical terms just returns a blank cell.).

Then if you drag that formula from B2 down to B1000, the formula will update row by row...so B3 would have =IF($A3<>"","Bruce",""), and cell B4 would have =IF($A4<>"","Bruce",""), etc. etc.

The VBA line in question selects the range, say B2:B1000, and applies the formula =IF($A2<>"",myValue,"") thus returning the myValue variable when the same row's column A is not empty.

(Don't get confused by the """".  Since our original formula contains quotes If($A2<>"" <-- in VBA you have to basically double up...otherwise VBA would interpret that line as just "=IF($A2<>"and then throw an error.  That """" & myValue & """" surrounds the myValue variable in quotes for the formula. If you just did =IF($A2<>""""," & myValue & ","""")" then you'll get an error, since myValue is being used like a named range/function/not a string.  Try it and see what I mean).

Body:
Current Outcome

A1     B1
Item   Deposit to
Apple  Trash
Banana
Grape

Private Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Enter Where", "Deposit to", Trash)
Range("B2").Value = myValue
End Sub

Trying to get the Value from the Input to auto-fill for the entire Column B as long as there is a value in Column A.

Attempted to place this with the Command Button, but can't seem to get it to work.

Sub test()
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
End Sub

Desired outcome

A1     B1
Item   Deposit to
Apple  Trash
Banana Trash
Grape  Trash

Is there a way to Prompt for value without the CommandButton?

At the moment, the CommandButton Works for the InputBox, but when i attempt the code to autofill it removes the Input and leaves blank.

Body:
You can use InputBox() anywhere in code, generally, to prompt for input. You can separate that from your Command Button code.

For the first part, you can use this formula.  Where there's a value in column A, put the input in column B:

Sub t()
Dim myValue As String
Dim lastCel As Range

Set lastCel = Range("A" & Rows.Count).End(xlUp)
myValue = InputBox("Enter Where", "Deposit to")

Range("B2:B" & lastCel.Row).Formula = "=IF($A2<>""""," & """" & myValue & """" & ","""")"
Range("B2:B" & lastCel.Row).Value = Range("B2:B" & lastCel.Row).Value

Range("B2").Value = myValue
End Sub

Edit:
The .Formula line is doing just as it reads - it's adding a formula to the range.

If you're in the worksheet, and in cell B2 enter the formula =IF($A2<>"","Bruce","") it will check if cell A2 is Empty.  If it's not empty, it will return Bruce.  If A2 is empty, will return an empty string "" (which in practical terms just returns a blank cell.).

Then if you drag that formula from B2 down to B1000, the formula will update row by row...so B3 would have =IF($A3<>"","Bruce",""), and cell B4 would have =IF($A4<>"","Bruce",""), etc. etc.

The VBA line in question selects the range, say B2:B1000, and applies the formula =IF($A2<>"",myValue,"") thus returning the myValue variable when the same row's column A is not empty.

(Don't get confused by the """".  Since our original formula contains quotes If($A2<>"" <-- in VBA you have to basically double up...otherwise VBA would interpret that line as just "=IF($A2<>"and then throw an error.  That """" & myValue & """" surrounds the myValue variable in quotes for the formula. If you just did =IF($A2<>""""," & myValue & ","""")" then you'll get an error, since myValue is being used like a named range/function/not a string.  Try it and see what I mean).


问:
Server Error in '/' Application. ASPNETDB.MDF ... ON PRODUCTION SERVER
I m getting the following error when i upload my site to Production Server using Database in App_Data ASPNETDB.MDF

Server Error in '/' Application.

Runtime Error

Description: An application error occurred on the server. The current
  custom error settings for this
  application prevent the details of the
  application error from being viewed
  remotely (for security reasons). It
  could, however, be viewed by browsers
  running on the local server machine.

Details: To enable the details of this specific error message to be
  viewable on remote machines, please
  create a  tag within a
  "web.config" configuration file
  located in the root directory of the
  current web application. This
   tag should then have
  its "mode" attribute set to "Off".

web.config:

```<code><!-- Web.Config Configuration File -->
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
</code>```

Notes: The current error page you are seeing can be replaced by a custom
  error page by modifying the
  "defaultRedirect" attribute of the
  application's
  configuration tag to point to a custom
  error page URL.

```<code><!-- Web.Config Configuration File -->
<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>
</code>```

I M CONFUSED WHY THIS ERROR OCCURED ?? AND HIW TO FIX THIS TO DISPLAY WEBSITE ...

答: Have a look at scottgu's article - Recipe: Deploying a SQL Database to a Remote Hosting Environment (Part 1) and an article from Scott Mitchell - Deploying a Local Database to a Remote Web Host</p>

Body:
I m getting the following error when i upload my site to Production Server using Database in App_Data ASPNETDB.MDF

Server Error in '/' Application.

Runtime Error

Description: An application error occurred on the server. The current
  custom error settings for this
  application prevent the details of the
  application error from being viewed
  remotely (for security reasons). It
  could, however, be viewed by browsers
  running on the local server machine.

Details: To enable the details of this specific error message to be
  viewable on remote machines, please
  create a  tag within a
  "web.config" configuration file
  located in the root directory of the
  current web application. This
   tag should then have
  its "mode" attribute set to "Off".

web.config:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Notes: The current error page you are seeing can be replaced by a custom
  error page by modifying the
  "defaultRedirect" attribute of the
  application's
  configuration tag to point to a custom
  error page URL.

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration>

I M CONFUSED WHY THIS ERROR OCCURED ?? AND HIW TO FIX THIS TO DISPLAY WEBSITE ...


问:
error C2059: syntax error: '}' C++
```<code>void walka(Postac p, Przeciwnik e, int walkaa)
{
    if (p.szybkosc < 0)
    {
        p.szybkosc = 0;
    }
walka:
    walkaa = p.szybkosc - e.szybkosc;
    if (walkaa > 0)
    {
        do
        {
            cout << "Zadajesz " << p.sila << " obrażeń." << endl << endl;
            e.zycie -= p.sila;
            cout << "Życie: " << p.zycie << " Życie przeciwnika: " << e.zycie << endl << endl;
            if (e.zycie <= 0)
            {
                cout << "Wygrałeś!" << endl;
                goto koniecwalki;
            }
            walkaa -= e.szybkosc;
        } while (walkaa > 0);
        goto walka;
    }
    else
    {
        do
        {
            cout << "Otrzymujesz " << e.sila << " obrażeń." << endl << endl;
            p.zycie -= e.sila;
            cout << "Życie: " << p.zycie << " Życie przeciwnika: " << e.zycie << endl << endl;
            if (p.zycie <= 0)
            {
                cout << "Zostałeś pokonany." << endl;
                goto koniecwalki2;
            }
            walkaa += p.szybkosc;
        } while (walkaa < 0);
    }
    goto walka;
koniecwalki:
    cout << "Przegrana" << endl;
koniecwalki2:

}
</code>```

1>Others.cpp(202): error C2059: syntax error: '}'

202nd line is the last curly bracket at the end of this function.
 I don't know why I'm getting this error now. I had it earlier a few times but every time it was just random additional bracket which I had to remove.

答:
The syntax error means that you have to use a null statement after the label

```<code>koniecwalki2: ;
             ^^^
}
</code>```

That is it is a statement that can be labeled (in C++ declarations are also statements while in C declarations are not statements).

Take into account that it is a bad idea to use goto statements. That makes the code difficult to read and modify.

Title: error C2059: syntax error: '}' C++

Body:
void walka(Postac p, Przeciwnik e, int walkaa)
{
    if (p.szybkosc < 0)
    {
        p.szybkosc = 0;
    }
walka:
    walkaa = p.szybkosc - e.szybkosc;
    if (walkaa > 0)
    {
        do
        {
            cout << "Zadajesz " << p.sila << " obrażeń." << endl << endl;
            e.zycie -= p.sila;
            cout << "Życie: " << p.zycie << " Życie przeciwnika: " << e.zycie << endl << endl;
            if (e.zycie <= 0)
            {
                cout << "Wygrałeś!" << endl;
                goto koniecwalki;
            }
            walkaa -= e.szybkosc;
        } while (walkaa > 0);
        goto walka;
    }
    else
    {
        do
        {
            cout << "Otrzymujesz " << e.sila << " obrażeń." << endl << endl;
            p.zycie -= e.sila;
            cout << "Życie: " << p.zycie << " Życie przeciwnika: " << e.zycie << endl << endl;
            if (p.zycie <= 0)
            {
                cout << "Zostałeś pokonany." << endl;
                goto koniecwalki2;
            }
            walkaa += p.szybkosc;
        } while (walkaa < 0);
    }
    goto walka;
koniecwalki:
    cout << "Przegrana" << endl;
koniecwalki2:

}

1>Others.cpp(202): error C2059: syntax error: '}'

202nd line is the last curly bracket at the end of this function.
 I don't know why I'm getting this error now. I had it earlier a few times but every time it was just random additional bracket which I had to remove.

Body:
The syntax error means that you have to use a null statement after the label

koniecwalki2: ;
             ^^^
}

That is it is a statement that can be labeled (in C++ declarations are also statements while in C declarations are not statements).

Take into account that it is a bad idea to use goto statements. That makes the code difficult to read and modify.


问:
android-sdk: android cmd not working globally
I've installed the Android SDK and faced this problem: I can execute cmd android only inside %PATH_TO_SDK%/tools folder.
Here is my PATH:

```<code>C:\Program Files\Git\cmd;C:\Program Files\TortoiseGit\bin;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files (x86)\Android\android-sdk\tools;C:\Program Files (x86)\Android\android-sdk\platform-tools;C:\ProgramData\Oracle\Java\javapath;c:\program files\graphicsmagick-1.3.21-q16;C:\Program Files\ImageMagick-6.9.2-Q16;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\dvurechenskii_aa\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\GitExtensions\;C:\Program Files (x86)\Skype\Phone\;C:\Users\dvurechenskii_aa\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Microsoft Emulator Manager\1.0\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\Doctrine extensions for PHP\;
</code>```

and ANDROID_HOME:

```<code>C:\Program Files (x86)\Android\android-sdk\
</code>```

what did i miss?

OS: windows 8.1

答:
I have resolve the problem by using these steps:

Go to: Start > Run > Type: sysdm.cpl

Once press enter, go to tabs: Advanced > Enviroment Variables...

Add new settings to System Variables

Put the new settings like this and click OK:

```<code>Variable name: ANDROID_HOME
Variable value: C:\Users\[PC NAME]\AppData\Local\Android\sdk
</code>```

Find the path variable and click edit, just add this line (do not delete the previous settings)

```<code>%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools
</code>```

There you go, you need to close your command prompt and reopen it

Was tested on WINDOWS

Body:
I've installed the Android SDK and faced this problem: I can execute cmd android only inside %PATH_TO_SDK%/tools folder.
Here is my PATH:

C:\Program Files\Git\cmd;C:\Program Files\TortoiseGit\bin;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files (x86)\Android\android-sdk\tools;C:\Program Files (x86)\Android\android-sdk\platform-tools;C:\ProgramData\Oracle\Java\javapath;c:\program files\graphicsmagick-1.3.21-q16;C:\Program Files\ImageMagick-6.9.2-Q16;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\dvurechenskii_aa\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\GitExtensions\;C:\Program Files (x86)\Skype\Phone\;C:\Users\dvurechenskii_aa\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Microsoft Emulator Manager\1.0\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 ^& MySQL Utilities 1.5\Doctrine extensions for PHP\;

and ANDROID_HOME:

C:\Program Files (x86)\Android\android-sdk\

what did i miss?

OS: windows 8.1

Body:
I have resolve the problem by using these steps:

Go to: Start > Run > Type: sysdm.cpl

Once press enter, go to tabs: Advanced > Enviroment Variables...

Add new settings to System Variables

Put the new settings like this and click OK:

Variable name: ANDROID_HOME
Variable value: C:\Users\[PC NAME]\AppData\Local\Android\sdk

Find the path variable and click edit, just add this line (do not delete the previous settings)

%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

There you go, you need to close your command prompt and reopen it

Was tested on WINDOWS


问:
Can't center a parent inline-block DIV with a child Inline-block DIV inside
I have 2 DIVs inside a parent div and they are displayed inline. The problem is that one of the 2 DIVS also needs to be displayed inline which prevents me from centering them both. Basically I need inline buttons on the left and text that is summing up the information of the page on the right. The text and the buttons must be centered.  https://jsfiddle.net/yLnt56ew/1/

.all_parent {
  text-align: center;
  margin: auto;
}

.Box_button {
  height: 200px;
  width: 200px;
  font-size: 20px;
  background-color: #4286f4;
  margin: 15px 15px;
  -webkit-box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  -moz-box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  vertical-align: middle;
  display: inline-block;
}

.Box_button:hover {
  background-color: #1e75ff;
}

.box_text {
  font-family: Arial;
  color: white;
  margin-top: 95px;
  text-align: center;
}

.Box_parent {
  max-width: 700px;
}

#project_line {
  display: inline-block;
  vertical-align: top;
}

.project_text {
  text-align: left;
  max-width: 350px;
  font-size: 19px;
  font-family: Arial;
  margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="all_parent">

  <div class="Box_parent" id="project_line">
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
    <a>
      <div class="Box_button">
        <div class="box_text"> TEST </div>
      </div>
    </a>
  </div>

  <div id="project_line" class="project_text">
    <h1>TEST </h1>
    <a> TEST</br> random text and some more random text! random text and some more random text! random text and some more random text! </br></br> TEST </br> random text and some more random text! </a>
  </div>
</div></code>```

答:
"all_parent" is an ID not a class.

Change .all_parent to #all_parent in your CSS and the centering works.

Also you should double check your markup because you're leaving out closing tags for elements.

Body:
I have 2 DIVs inside a parent div and they are displayed inline. The problem is that one of the 2 DIVS also needs to be displayed inline which prevents me from centering them both. Basically I need inline buttons on the left and text that is summing up the information of the page on the right. The text and the buttons must be centered.  https://jsfiddle.net/yLnt56ew/1/

.all_parent {
  text-align: center;
  margin: auto;
}

.Box_button {
  height: 200px;
  width: 200px;
  font-size: 20px;
  background-color: #4286f4;
  margin: 15px 15px;
  -webkit-box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  -moz-box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  box-shadow: 0px 0px 13px 0px rgba(50, 50, 50, 0.75);
  vertical-align: middle;
  display: inline-block;
}

.Box_button:hover {
  background-color: #1e75ff;
}

.box_text {
  font-family: Arial;
  color: white;
  margin-top: 95px;
  text-align: center;
}

.Box_parent {
  max-width: 700px;
}

#project_line {
  display: inline-block;
  vertical-align: top;
}

.project_text {
  text-align: left;
  max-width: 350px;
  font-size: 19px;
  font-family: Arial;
  margin-left: 50px;
}

 TEST

 TEST

 TEST

 TEST

 TEST

 TEST

TEST

     TEST
 random text and some more random text! random text and some more random text! random text and some more random text!

 TEST
 random text and some more random text!


问:
KafkaStreams applications
I run two kafka streams applications separately, each one in a different JVM instance and they are working fine. Once I run the applications in the same JVM instance, the second application is not working (neither consuming nor producing data). Are there any limitations about running two separate apps in the same JVM instance? Does this also happen for kafka consumers?</p>

答:
It should work to put multiple KafkaStreams instances into the same JVM. But it might be easier to just increase the number of thread within one instance.

Note: the number of thread over all instances that you can utilize is limited by the number of input partitions of you input topics (this is not quite exact but a good rule of thumb). Do you have enough partitions in your input topic? Do you see that some partitions are not assigned to an instance an not processed?

Also note, Kafka Stream parallelizes per threads -- this means, if you have 2 instances with 2 threads each, and only 2 input topic partitions, it can happen that both partitions are assigned to the two thread of one instance while the two thread of the other instance are idle. During runtime, we only "see" thread and don't know if they run within the same or different KafkaStreams instances.

Title: KafkaStreams applications


问:
too high implementation for minSDK in build.gradle created by Android Studio
I've just created my first Android Studio project. I chose min SDK 15. I'm worried why then compile SDK by default is higher.. Is it secure? Will my app run on devices with API 15 in this configuration? But the real problem occurred when I switched my compileSdkVersion and targetSdkVersion to 24. Errors everywhere and info that implementation 'com.android.support:appcompat-v7:26.1.0' is too high for my target SDK. So why on earth Android Studio put there so high implementation if the min SDK is lower?

TL;DR:
Why implementation is so high? Will it work in this configuration with min API?? Why Android Studio works like this?

build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.q_back.audiocrator"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答: Its ok, and in fact normal for the compileSDK to be bigger than the minimum.  The library version for the support version should match your compileSDK.  Either upgrade to 26, or downgrade the support library.</p>

Body:
I've just created my first Android Studio project. I chose min SDK 15. I'm worried why then compile SDK by default is higher.. Is it secure? Will my app run on devices with API 15 in this configuration? But the real problem occurred when I switched my compileSdkVersion and targetSdkVersion to 24. Errors everywhere and info that implementation 'com.android.support:appcompat-v7:26.1.0' is too high for my target SDK. So why on earth Android Studio put there so high implementation if the min SDK is lower?

TL;DR:
Why implementation is so high? Will it work in this configuration with min API?? Why Android Studio works like this?

build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.q_back.audiocrator"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I think the a-ha moment for me, was when I stopped thinking about OOP in terms of cars and blueprints, and whatever other metaphors my teachers were trying to crowbar into my brain, and started thinking about it in terms of its practical application in real code.

The first object I wrote in which I really got it, was a little class that created a database connection, and encapsulated a bunch of methods for doing SQL queries. After that point OOP went from something the teachers talked about, into being something that was actually useful to me and my code.

So, my advice would be, just to keep on going, keep learning and, most importantly, write as much code as you can. What makes something click for me, or for everyone else, may not make it click for you, so you need to forge your own path.

As someone else suggested, maybe drop C# for a little while, and try a different language. Broaden your horizons, maybe learn some C++, or have a mess around with Python or Ruby. You will come back to C# with a fresh perspective and clear palette, and as a better programmer, and maybe things will become more clickable for you then.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Alex McBride


问:
Why is TypedReference behind the scenes? It's so fast and safe... almost magical!
Warning: This question is a bit heretical... religious programmers always abiding by good practices, please don't read it. :)

Does anyone know why the use of TypedReference is so discouraged (implicitly, by lack of documentation)?

I've found great uses for it, such as when passing generic parameters through functions that shouldn't be generic (when using an object might be overkill or slow, if you need a value type), for when you need an opaque pointer, or for when you need to access an element of an array quickly, whose specs you find at runtime (using Array.InternalGetReference). Since the CLR doesn't even allow incorrect usage of this type, why is it discouraged? It doesn't seem to be unsafe or anything...

Other uses I've found for TypedReference:

"Specializing" generics in C# (this is type-safe):

```<code>static void foo<T>(ref T value)
{
    //This is the ONLY way to treat value as int, without boxing/unboxing objects
    if (value is int)
    { __refvalue(__makeref(value), int) = 1; }
    else { value = default(T); }
}
</code>```

Writing code that works with generic pointers (this is very unsafe if misused, but fast and safe if used correctly):

```<code>//This bypasses the restriction that you can't have a pointer to T,
//letting you write very high-performance generic code.
//It's dangerous if you don't know what you're doing, but very worth if you do.
static T Read<T>(IntPtr address)
{
    var obj = default(T);
    var tr = __makeref(obj);

    //This is equivalent to shooting yourself in the foot
    //but it's the only high-perf solution in some cases
    //it sets the first field of the TypedReference (which is a pointer)
    //to the address you give it, then it dereferences the value.
    //Better be 10000% sure that your type T is unmanaged/blittable...
    unsafe { *(IntPtr*)(&tr) = address; }

    return __refvalue(tr, T);
}
</code>```

Writing a method version of the sizeof instruction, which can be occasionally useful:

```<code>static class ArrayOfTwoElements<T> { static readonly Value = new T[2]; }

static uint SizeOf<T>()
{
    unsafe
    {
        TypedReference
            elem1 = __makeref(ArrayOfTwoElements<T>.Value[0] ),
            elem2 = __makeref(ArrayOfTwoElements<T>.Value[1] );
        unsafe
        { return (uint)((byte*)*(IntPtr*)(&elem2) - (byte*)*(IntPtr*)(&elem1)); }
    }
}
</code>```

Writing a method that passes a "state" parameter that wants to avoid boxing:

```<code>static void call(Action<int, TypedReference> action, TypedReference state)
{
    //Note: I could've said "object" instead of "TypedReference",
    //but if I had, then the user would've had to box any value types
    try
    {
        action(0, state);
    }
    finally { /*Do any cleanup needed*/ }
}
</code>```

So why are uses like this "discouraged" (by lack of documentation)? Any particular safety reasons? It seems perfectly safe and verifiable if it's not mixed with pointers (which aren't safe or verifiable anyway)...

Update:

Sample code to show that, indeed, TypedReference can be twice as fast (or more):

```<code>using System;
using System.Collections.Generic;
static class Program
{
    static void Set1<T>(T[] a, int i, int v)
    { __refvalue(__makeref(a[i]), int) = v; }

    static void Set2<T>(T[] a, int i, int v)
    { a[i] = (T)(object)v; }

    static void Main(string[] args)
    {
        var root = new List<object>();
        var rand = new Random();
        for (int i = 0; i < 1024; i++)
        { root.Add(new byte[rand.Next(1024 * 64)]); }
        //The above code is to put just a bit of pressure on the GC

        var arr = new int[5];
        int start;
        const int COUNT = 40000000;

        start = Environment.TickCount;
        for (int i = 0; i < COUNT; i++)
        { Set1(arr, 0, i); }
        Console.WriteLine("Using TypedReference:  {0} ticks",
                          Environment.TickCount - start);
        start = Environment.TickCount;
        for (int i = 0; i < COUNT; i++)
        { Set2(arr, 0, i); }
        Console.WriteLine("Using boxing/unboxing: {0} ticks",
                          Environment.TickCount - start);

        //Output Using TypedReference:  156 ticks
        //Output Using boxing/unboxing: 484 ticks
    }
}
</code>```

(Edit: I edited the benchmark above, since the last version of the post used a debug version of the code [I forgot to change it to release], and put no pressure on the GC. This version is a bit more realistic, and on my system, it's more than three times faster with TypedReference on average.)

答:
Well, I'm no Eric Lippert, so I can't speak directly of Microsoft's motivations, but if I were to venture a guess, I'd say that TypedReference et al. aren't well documented because, frankly, you don't need them.

Every use you mentioned for these features can be accomplished without them, albeit at a performance penalty in some cases.  But C# (and .NET in general) isn't designed to be a high-performance language.  (I'm guessing that "faster than Java" was the performance goal.)

That's not to say that certain performance considerations haven't been afforded.  Indeed, such features as pointers, stackalloc, and certain optimized framework functions exist largely to boost performance in certain situations.

Generics, which I'd say have the primary benefit of type safety, also improve performance similarly to TypedReference by avoiding boxing and unboxing.  In fact, I was wondering why you'd prefer this:

```<code>static void call(Action<int, TypedReference> action, TypedReference state){
    action(0, state);
}
</code>```

to this:

```<code>static void call<T>(Action<int, T> action, T state){
    action(0, state);
}
</code>```

The trade-offs, as I see them, are that the former requires fewer JITs (and, it follows, less memory), while the latter is more familiar and, I would assume, slightly faster (by avoiding pointer dereferencing).

I'd call TypedReference and friends implementation details.  You've pointed out some neat uses for them, and I think they're worth exploring, but the usual caveat of relying on implementation details applies—the next version may break your code.

Body:
Warning: This question is a bit heretical... religious programmers always abiding by good practices, please don't read it. :)

Does anyone know why the use of TypedReference is so discouraged (implicitly, by lack of documentation)?

I've found great uses for it, such as when passing generic parameters through functions that shouldn't be generic (when using an object might be overkill or slow, if you need a value type), for when you need an opaque pointer, or for when you need to access an element of an array quickly, whose specs you find at runtime (using Array.InternalGetReference). Since the CLR doesn't even allow incorrect usage of this type, why is it discouraged? It doesn't seem to be unsafe or anything...

Other uses I've found for TypedReference:

"Specializing" generics in C# (this is type-safe):

static void foo<T>(ref T value)
{
    //This is the ONLY way to treat value as int, without boxing/unboxing objects
    if (value is int)
    { __refvalue(__makeref(value), int) = 1; }
    else { value = default(T); }
}

Writing code that works with generic pointers (this is very unsafe if misused, but fast and safe if used correctly):

//This bypasses the restriction that you can't have a pointer to T,
//letting you write very high-performance generic code.
//It's dangerous if you don't know what you're doing, but very worth if you do.
static T Read<T>(IntPtr address)
{
    var obj = default(T);
    var tr = __makeref(obj);

    //This is equivalent to shooting yourself in the foot
    //but it's the only high-perf solution in some cases
    //it sets the first field of the TypedReference (which is a pointer)
    //to the address you give it, then it dereferences the value.
    //Better be 10000% sure that your type T is unmanaged/blittable...
    unsafe { *(IntPtr*)(&tr) = address; }

    return __refvalue(tr, T);
}

Writing a method version of the sizeof instruction, which can be occasionally useful:

static class ArrayOfTwoElements<T> { static readonly Value = new T[2]; }

static uint SizeOf<T>()
{
    unsafe
    {
        TypedReference
            elem1 = __makeref(ArrayOfTwoElements<T>.Value[0] ),
            elem2 = __makeref(ArrayOfTwoElements<T>.Value[1] );
        unsafe
        { return (uint)((byte*)*(IntPtr*)(&elem2) - (byte*)*(IntPtr*)(&elem1)); }
    }
}

Writing a method that passes a "state" parameter that wants to avoid boxing:

static void call(Action<int, TypedReference> action, TypedReference state)
{
    //Note: I could've said "object" instead of "TypedReference",
    //but if I had, then the user would've had to box any value types
    try
    {
        action(0, state);
    }
    finally { /*Do any cleanup needed*/ }
}

So why are uses like this "discouraged" (by lack of documentation)? Any particular safety reasons? It seems perfectly safe and verifiable if it's not mixed with pointers (which aren't safe or verifiable anyway)...

Update:

Sample code to show that, indeed, TypedReference can be twice as fast (or more):

using System;
using System.Collections.Generic;
static class Program
{
    static void Set1<T>(T[] a, int i, int v)
    { __refvalue(__makeref(a[i]), int) = v; }

    static void Set2<T>(T[] a, int i, int v)
    { a[i] = (T)(object)v; }

    static void Main(string[] args)
    {
        var root = new List<object>();
        var rand = new Random();
        for (int i = 0; i < 1024; i++)
        { root.Add(new byte[rand.Next(1024 * 64)]); }
        //The above code is to put just a bit of pressure on the GC

        var arr = new int[5];
        int start;
        const int COUNT = 40000000;

        start = Environment.TickCount;
        for (int i = 0; i < COUNT; i++)
        { Set1(arr, 0, i); }
        Console.WriteLine("Using TypedReference:  {0} ticks",
                          Environment.TickCount - start);
        start = Environment.TickCount;
        for (int i = 0; i < COUNT; i++)
        { Set2(arr, 0, i); }
        Console.WriteLine("Using boxing/unboxing: {0} ticks",
                          Environment.TickCount - start);

        //Output Using TypedReference:  156 ticks
        //Output Using boxing/unboxing: 484 ticks
    }
}

(Edit: I edited the benchmark above, since the last version of the post used a debug version of the code [I forgot to change it to release], and put no pressure on the GC. This version is a bit more realistic, and on my system, it's more than three times faster with TypedReference on average.)

Body:
Well, I'm no Eric Lippert, so I can't speak directly of Microsoft's motivations, but if I were to venture a guess, I'd say that TypedReference et al. aren't well documented because, frankly, you don't need them.

Every use you mentioned for these features can be accomplished without them, albeit at a performance penalty in some cases.  But C# (and .NET in general) isn't designed to be a high-performance language.  (I'm guessing that "faster than Java" was the performance goal.)

That's not to say that certain performance considerations haven't been afforded.  Indeed, such features as pointers, stackalloc, and certain optimized framework functions exist largely to boost performance in certain situations.

Generics, which I'd say have the primary benefit of type safety, also improve performance similarly to TypedReference by avoiding boxing and unboxing.  In fact, I was wondering why you'd prefer this:

static void call(Action<int, TypedReference> action, TypedReference state){
    action(0, state);
}

to this:

static void call<T>(Action<int, T> action, T state){
    action(0, state);
}

The trade-offs, as I see them, are that the former requires fewer JITs (and, it follows, less memory), while the latter is more familiar and, I would assume, slightly faster (by avoiding pointer dereferencing).

I'd call TypedReference and friends implementation details.  You've pointed out some neat uses for them, and I think they're worth exploring, but the usual caveat of relying on implementation details applies—the next version may break your code.


问:
git command "git checkout master || :"
I am trying to understand this git command.
I have got a software repository which has got submodules and that submodule points to another submodule. In order to check out, this command is used -

```<code>git submodule foreach --recursive 'git checkout master || :'
</code>```

This question is about understanding this command.
What does "|| :" means in this command? I am asking this question so that I can be more flexible in changing these commands according to the need.

In this command - foreach, means for each submodule found go and do a checkout of master but what "|| and :" means here.

答: cmd ||: is just a way to ensure that the command always succeeds.  If cmd fails, then : is executed and succeeds, so that $? will always be 0.  So basically your submodule foreach is ignoring any errors checking out master.

Title: git command "git checkout master || :"

Body:
I am trying to understand this git command.
I have got a software repository which has got submodules and that submodule points to another submodule. In order to check out, this command is used -

git submodule foreach --recursive 'git checkout master || :'

This question is about understanding this command.
What does "|| :" means in this command? I am asking this question so that I can be more flexible in changing these commands according to the need.

In this command - foreach, means for each submodule found go and do a checkout of master but what "|| and :" means here.


问:
Using AVCaptureVideoDataOutputSampleBufferDelegate without a preview window
I'm working on a Swift-based macOS app where I need to capture video input, but not display it on the screen...rather than display the video, I want to send the buffered data for processing elsewhere, and eventually display it on an object in a SceneKit scene.

I have a CameraInput class that has a prepareCamera method:

```<code>    fileprivate func prepareCamera() {
        self.videoSession = AVCaptureSession()
        self.videoSession.sessionPreset = AVCaptureSession.Preset.photo

        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] {
            for device in devices {
                if device.hasMediaType(AVMediaType.video) {
                    cameraDevice = device

                    if cameraDevice != nil  {
                        do {
                            let input = try AVCaptureDeviceInput(device: cameraDevice)

                            if videoSession.canAddInput(input) {
                                videoSession.addInput(input)
                            }

                           } catch {
                            print(error.localizedDescription)
                        }
                    }
                }
            }

            let videoOutput = AVCaptureVideoDataOutput()
            videoOutput.setSampleBufferDelegate(self as AVCaptureVideoDataOutputSampleBufferDelegate, queue: DispatchQueue(label: "sample buffer delegate", attributes: []))
            if videoSession.canAddOutput(videoOutput) {
                videoSession.addOutput(videoOutput)
            }
        }
    }
</code>```

And a startSession method that starts the AVCaptureSession session:

```<code>fileprivate func startSession() {
    if let videoSession = videoSession {
        if !videoSession.isRunning {
            self.videoInputRunning = true
            videoSession.startRunning()
        }
    }
}
</code>```

I also implement AVCaptureVideoDataOutputSampleBufferDelegate, where I intend to capture the CMSampleBuffer for later use:

```<code>extension CameraInput: AVCaptureVideoDataOutputSampleBufferDelegate {

    internal func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
        print(Date())
    }
}
</code>```

However, the delegate is never called. Is this a situation where I have to display the video output in order for this to be called?

答:
None of your issues have to do with whether (or not) you display a preview of captured video.

If you're on Swift 4 (and it looks like you are), the delegate method signature you're looking to implement isn't captureOutput(_:didOutputSampleBuffer:from:), it's this:

```<code>optional func captureOutput(_ output: AVCaptureOutput,
              didOutput sampleBuffer: CMSampleBuffer,
                     from connection: AVCaptureConnection)
</code>```

Unrelated tips:

Namespaced constants mean you can be more brief if you like; e.g. videoSession.sessionPreset = .photo

AVCaptureDevice.devices() is deprecated. Instead of calling that and looping through devices yourself, just ask AVCaptureDevice for exactly the kind of device you want:

```<code>let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
                                       for: .video, position: .back)
</code>```

You don't need the as cast in videoOutput.setSampleBufferDelegate(self as AVCaptureVideoDataOutputSampleBufferDelegate if your class already declares conformance to the AVCaptureVideoDataOutputSampleBufferDelegate protocol.

Finally, if you're just looking to get the live-from-camera video mapped onto some part of a SceneKit scene, note that in iOS 11 you can assign an AVCaptureDevice to an SCNMaterialProperty's contents directly — no need to grab, process, and move pixel buffers yourself.

Body:
I'm working on a Swift-based macOS app where I need to capture video input, but not display it on the screen...rather than display the video, I want to send the buffered data for processing elsewhere, and eventually display it on an object in a SceneKit scene.

I have a CameraInput class that has a prepareCamera method:

    fileprivate func prepareCamera() {
        self.videoSession = AVCaptureSession()
        self.videoSession.sessionPreset = AVCaptureSession.Preset.photo

        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] {
            for device in devices {
                if device.hasMediaType(AVMediaType.video) {
                    cameraDevice = device

                    if cameraDevice != nil  {
                        do {
                            let input = try AVCaptureDeviceInput(device: cameraDevice)

                            if videoSession.canAddInput(input) {
                                videoSession.addInput(input)
                            }

                           } catch {
                            print(error.localizedDescription)
                        }
                    }
                }
            }

            let videoOutput = AVCaptureVideoDataOutput()
            videoOutput.setSampleBufferDelegate(self as AVCaptureVideoDataOutputSampleBufferDelegate, queue: DispatchQueue(label: "sample buffer delegate", attributes: []))
            if videoSession.canAddOutput(videoOutput) {
                videoSession.addOutput(videoOutput)
            }
        }
    }

And a startSession method that starts the AVCaptureSession session:

fileprivate func startSession() {
    if let videoSession = videoSession {
        if !videoSession.isRunning {
            self.videoInputRunning = true
            videoSession.startRunning()
        }
    }
}

I also implement AVCaptureVideoDataOutputSampleBufferDelegate, where I intend to capture the CMSampleBuffer for later use:

extension CameraInput: AVCaptureVideoDataOutputSampleBufferDelegate {

    internal func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
        print(Date())
    }
}

However, the delegate is never called. Is this a situation where I have to display the video output in order for this to be called?

Body:
None of your issues have to do with whether (or not) you display a preview of captured video.

If you're on Swift 4 (and it looks like you are), the delegate method signature you're looking to implement isn't captureOutput(_:didOutputSampleBuffer:from:), it's this:

optional func captureOutput(_ output: AVCaptureOutput,
              didOutput sampleBuffer: CMSampleBuffer,
                     from connection: AVCaptureConnection)

Unrelated tips:

Namespaced constants mean you can be more brief if you like; e.g. videoSession.sessionPreset = .photo

AVCaptureDevice.devices() is deprecated. Instead of calling that and looping through devices yourself, just ask AVCaptureDevice for exactly the kind of device you want:

let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
                                       for: .video, position: .back)

You don't need the as cast in videoOutput.setSampleBufferDelegate(self as AVCaptureVideoDataOutputSampleBufferDelegate if your class already declares conformance to the AVCaptureVideoDataOutputSampleBufferDelegate protocol.

Finally, if you're just looking to get the live-from-camera video mapped onto some part of a SceneKit scene, note that in iOS 11 you can assign an AVCaptureDevice to an SCNMaterialProperty's contents directly — no need to grab, process, and move pixel buffers yourself.


问:
MySql: Inser Into ... Select ... Where return #1054 error
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

```<code>ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.
</code>```

The second table is called "ar_geozone" and has the following structure:

```<code>country;
code_city;
name_city;
longitude;
latitude.
</code>```

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

```<code>INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries
</code>```

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.

答:
Use a join or subquery:

```<code>INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
    SELECT code_city, name_city, longitude, latitude
    FROM ar_geozone ag
    WHERE EXISTS (SELECT 1
                  FROM countries c
                  WHERE ag.country LIKE c.code_countries
                 );
</code>```

The LIKE c.code_countries is a bit suspicious.  Normally, you would just use = for the comparison.

Body:
I have two tables with a column both containing the same data.

The first table is called "countries" and has the following structure:

ID -> primary key;
name_countries;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city.

The second table is called "ar_geozone" and has the following structure:

country;
code_city;
name_city;
longitude;
latitude.

I would like to copy all data from "ar_geozone" to "countries", for those rows where there is a match between "ar_geozone.country" and "countries.code_countries".

But when I use this SQL string,

INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
SELECT code_city, name_city, longitude, latitude FROM ar_geozone
WHERE ar_geozone.country LIKE countries.code_countries

the system returns the error: # 1054 - Unknown column 'countries.code_countries' in 'where clause'.

Body:
Use a join or subquery:

INSERT INTO countries (code_city, name_city, longitude_city, latitude_city)
    SELECT code_city, name_city, longitude, latitude
    FROM ar_geozone ag
    WHERE EXISTS (SELECT 1
                  FROM countries c
                  WHERE ag.country LIKE c.code_countries
                 );

The LIKE c.code_countries is a bit suspicious.  Normally, you would just use = for the comparison.


问:
Eclipse Color themes does not change font color
I am using Eclipse Mars 4.5.1 on a Macbook to work with a Fortran Project. I recently installed Color themes from the Eclipse marketplace. I can see the list of available color themes. If I select one and try to apply it, only the background and the line number change while the font color remains the default one. For example the image shows the editor with the Monokai theme (which on the preview looks very different), all other themes behave the same way. How can I make the color theme apply to the font too?

答:
To change Photran colors easyly, just edit the file:

$WORKSPACE/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.photran.core.prefs

And just paste this (matches with a dark theme):

```<code>eclipse.preferences.version=1
integer.fixedformcommentcolum=72
integer.tabwidth=0
rgb.comments=199,221,12
rgb.cpp=141,203,226
rgb.directives=141,203,226
rgb.identifiers=255,255,255
rgb.intrinsics=141,203,226
rgb.keywords=210,82,82
rgb.nums_punc=127,179,71
rgb.strings=255,198,0
string.modelbuilder=defaultModelBilder
</code>```

Body:
To change Photran colors easyly, just edit the file:

$WORKSPACE/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.photran.core.prefs

And just paste this (matches with a dark theme):

eclipse.preferences.version=1
integer.fixedformcommentcolum=72
integer.tabwidth=0
rgb.comments=199,221,12
rgb.cpp=141,203,226
rgb.directives=141,203,226
rgb.identifiers=255,255,255
rgb.intrinsics=141,203,226
rgb.keywords=210,82,82
rgb.nums_punc=127,179,71
rgb.strings=255,198,0
string.modelbuilder=defaultModelBilder


问:
NodeJs Passport performs CORS pre-flight if request comes from VueJS
I am writing a NodeJS / Express backend that uses Passport with the Saml-Stategy. I am using an external Identity Provider and VueJs as a frontend.

If I do an API request to the backend from the browser (Chrome + IE) everything works fine. The request goes to the backend, goes to the IdP as GET request and comes back authenticated.

But if I load the VueJs app that does the same request, passport makes a CORS pre-flight (OPTIONS) request that comes back from the IdP as 404, because OPTIONS is not supported. I tried Vue-Resource and Axios, both the same result.

Unfortunately I can not change any settings on the IdP. But why does my passport in the backend treats the requests differently? Any Ideas?

I compared the request headers from the API call and VueJs, and I cant find any headers that would cause the pre-flight.

Repository: https://github.com/tmschbgr/NodePassportExample

Versions:

Node: 8.9.0

Express: 4.16.2

Passport: ^0.4.0

Passport-saml: ^0.31.0

Vue: ^2.4.4

Axios: ^0.17.1

答:
I found out that it was causing due to a timing issue.

It works with the following logic:

Request comes to Backend, check if authenticated

If not, go to IdP and come back. If successful redirect to /

Serve the static file AFTER the authentication check. That way the app only gets served when the user is authenticated.


问:
copy elision of temporary object
CPP Refs states:

— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

Let's say I have some test code:

```<code>#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class MyVector : public vector<T>
{
public:
    MyVector()
    {
        cout << "MyVector()" << endl;
    }

    MyVector(const MyVector& right):
        vector<T>(right)
    {
        cout << "MyVector(const MV&)" << endl;
    }

    MyVector(MyVector&& right) :
        vector<T>(right)
    {
        cout << "MyVector(MV&&)" << endl;
    }

};

class A
{
public:
    A() = default;
    A(MyVector<char> vec) :
        _vec(std::move(vec))
    {
        cout << "A(MyVec)" << endl;
    }
private:
    MyVector<char> _vec;
};

MyVector<char> funcElision()
{
    cout << "\nElision" << endl;
    MyVector<char> tmp;
    tmp.emplace_back('a');
    return tmp;
}

A funcElisionExternal()
{
    cout << "\nElision external test" << endl;
    return A(funcElision());
}

A funcElisionInternal()
{
    cout << "Elision internal test" << endl;
    MyVector<char> tmp;
    tmp.emplace_back('a');
    return A(tmp);
}

int main()
{
    auto a = funcElisionInternal();
    auto b = funcElisionExternal();
}
</code>```

The output of the test is:

```<code>Elision internal test
MyVector()
MyVector(const MV&)
MyVector(MV&&)
A(MyVec)

Elision external test

Elision
MyVector()
MyVector(MV&&)
A(MyVec)
 End
</code>```

The function elisionExternal does work as expected, but i don't know why the elisionInternal is doing the copy operation, since the MyVec is temporary object?

答:
Several things are going on here.

funcElision is omitting the copy in its return because of Named Return Value Optimization (NRVO), a special rule for named return values when: "a function returns a class type by value, and the return statement's expression is the name of a non-volatile object with automatic storage duration, which isn't a function parameter, or a catch clause parameter, and which has the same type (ignoring top-level cv-qualification) as the return type of the function."

In funcElisionExternal, the return value of funcElision is used as a "nameless temporary", which can specifically elide copies (and moves post-C++11). An A is then constructed and returned using Return Value Optimization (RVO) since it is also a nameless temporary.

In funcElisionInternal, tmp is a named temporary, so it can only elide copies with NRVO. However, it is not the value that is being returned, and does not have the same type as the function's return signature - it is passed to A's constructor first. So it cannot use NRVO.

Other rules for copy elision have to do with throw expressions and exceptions, so are not applicable here.

See cppreference's page on copy elision for more.

Title: copy elision of temporary object

Body:
CPP Refs states:

— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

Let's say I have some test code:

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class MyVector : public vector<T>
{
public:
    MyVector()
    {
        cout << "MyVector()" << endl;
    }

    MyVector(const MyVector& right):
        vector<T>(right)
    {
        cout << "MyVector(const MV&)" << endl;
    }

    MyVector(MyVector&& right) :
        vector<T>(right)
    {
        cout << "MyVector(MV&&)" << endl;
    }

};

class A
{
public:
    A() = default;
    A(MyVector<char> vec) :
        _vec(std::move(vec))
    {
        cout << "A(MyVec)" << endl;
    }
private:
    MyVector<char> _vec;
};

MyVector<char> funcElision()
{
    cout << "\nElision" << endl;
    MyVector<char> tmp;
    tmp.emplace_back('a');
    return tmp;
}

A funcElisionExternal()
{
    cout << "\nElision external test" << endl;
    return A(funcElision());
}

A funcElisionInternal()
{
    cout << "Elision internal test" << endl;
    MyVector<char> tmp;
    tmp.emplace_back('a');
    return A(tmp);
}

int main()
{
    auto a = funcElisionInternal();
    auto b = funcElisionExternal();
}

The output of the test is:

Elision internal test
MyVector()
MyVector(const MV&)
MyVector(MV&&)
A(MyVec)

Elision external test

Elision
MyVector()
MyVector(MV&&)
A(MyVec)
 End

The function elisionExternal does work as expected, but i don't know why the elisionInternal is doing the copy operation, since the MyVec is temporary object?


答:
: is a shell command that does nothing and always succeeds (similar to true). So by adding

|| : to a commandline, the overall command will always be successful, even if the command on the left side of the || failed. In this case it causes git submodule foreach to continue even if one of the submodules isn't able to checkout master.

This usage is suggested by the git documentation:

A non-zero return from the command in any submodule causes the processing to terminate. This can be overridden by adding || : to the end of the command.

Title: git command "git checkout master || :"


问:
what is a good schema design for a loan origination system?
I am designing a loan origination system which would allow it's users to create loans, draw repayment schedule of the loan depending on the loan product parameters. I should also be able to add penalty, fees etc. Rescheduling loan should be possibility. I also need a loan schedule to do fast reporting.

I have a loans table, loan product table, payment schedule table and loan history table etc. I am not able to understand how I can design ahead this schema to keep it from changing too much.

I am doing this in ruby, rails3 and datamapper.

答:
Except in the most tightly specified applications, I'm not sure you can design a schema that won't change much.  What you can do is to make schemas that are not brittle, schemas that allow for change to happen.  For the most part, that means.

Include only the data you know you need to meet today's requirements

Normalize.

Write automated tests.

The first rule is akin to "do the simplest thing possible," or "you ain't gonna need it," the rule that programmers use to avoid code bloat.  Smaller schemas, like smaller code bases, need less effort to change.  The second (normalize) is analagous to the Don't Repeat Yourself (DRY) principle, also known as "once and only once," another rule used to make code cheaper to change.  The third rule (tests) is how programmers make refactoring possible without worrying about breaking everything.  By tests, I mean testing the code that uses the schema, but also testing the schema itself: triggers, rules, cascading deletes, &c. can be tested, and when tested, it is easier to change them in response to changing requirements.

There are excuses, in the database world, for breaking these rules.  The reason to break rule 1 (do the simplest thing/YAGNI) is that some data will be easier to collect from the beginning, and difficult or  perhaps even impossible to collect if you decide you do need it later.  Still, think twice before giving in to this excuse.  You can almost always deal without too much fuss with gaps in the data caused by adding columns or tables later, but if you include today data you might only need tomorrow, you will be paying for it every time you change the schema.  Each bit of data you include that you end up not needing was nothing but cost with no benefit.  Perhaps more significantly, extra data can have a terrible effect upon performance, since it reduces the number of records that can fit in memory.  Even though databases go through great pains to give good performance when reading from disk, their best performance comes from having enough memory (or little enough data) so that all or most of the working set will fit in RAM.

The excuse for breaking rule 2 (normalization) is performance: "Data warehouse" applications sometimes require denormalization in cases where many-table joins make a database slow and cranky.  I'd want to be certain it was needed before denormalizing, since it's not free: data that exists in more than once place makes the schema more difficult to change, and trades off speed of queries for more work when inserting & updating.

I don't know of an excuse for breaking rule 3 (testing), or at least not a good one, but that doesn't mean there isn't one.

Martin Fowler writes "Evolutionary Database Design".  Scott Amber and Pramod Sadalage have a book on Refactoring Databases.  See also a summary/cheat sheet of the book's refactorings.


答:
```<code>git submodule foreach --recursive '<command>'
</code>```

This runs the <command> in each checked out submodule.

So that leaves the command itself to understand:

```<code>git checkout master || :
</code>```

git checkout master should be pretty clear.

|| is an OR control character. For command1 || command2, command2 is executed if command1 returned a non-zero exit status. So basically when command1 failed.

So in this case, : runs when git checkout master failed.

The colon on the other hand is an alias for true in Bash. So effectively, this command will not do anything, making the full command run git checkout master if it can or it will silently fail.

Title: git command "git checkout master || :"

Body:
git submodule foreach --recursive '<command>'

This runs the <command> in each checked out submodule.

So that leaves the command itself to understand:

git checkout master || :

git checkout master should be pretty clear.

|| is an OR control character. For command1 || command2, command2 is executed if command1 returned a non-zero exit status. So basically when command1 failed.

So in this case, : runs when git checkout master failed.

The colon on the other hand is an alias for true in Bash. So effectively, this command will not do anything, making the full command run git checkout master if it can or it will silently fail.