问:
Android translate animation - permanently move View to new position using AnimationListener
I have android translate Animation. I have an ImageView with random generated position (next1, next2). I am calling void every 3 seconds. It generates new position of the View and then make animation and move View to destination position. Translate animation has  AnimationListener implemented. When the animation finish,  I move View permanently to the new position (in OnAnimationEnd). My problem is that animation position does not correspond with setting layoutParams positions. When animation end, it makes jump to a new position, which is about 50-100 pixels far. I think the positions should be the same because I use same values (next1, next2) in both situations. Please can you show me the way to find sollution ?

```<code> FrameLayout.LayoutParams pozice_motyl = (FrameLayout.LayoutParams)  pozadi_motyl.getLayoutParams();
            TranslateAnimation anim = new TranslateAnimation(Animation.ABSOLUTE,pozice_motyl.leftMargin, Animation.ABSOLUTE, next1, Animation.ABSOLUTE, pozice_motyl.topMargin, Animation.ABSOLUTE, next2);
            anim.setDuration(1000);
            anim.setFillAfter(true);
            anim.setFillEnabled(true);

            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(100, 100);

                    layoutParams.leftMargin = (int)(next1);
                    layoutParams.topMargin = (int)(next2);
                    pozadi_motyl.setLayoutParams(layoutParams);

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            pozadi_motyl.startAnimation(anim);
</code>```

Here is XML layout:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/pozadi0"
    android:gravity="center_vertical"
    android:layout_gravity="center_vertical"
    android:background="@drawable/pozadi2"
    >

<LinearLayout
android:id="@+id/pozadi_motyl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

  <ImageView android:id="@+id/obrazek_motyl"
             android:src="@drawable/motyl"
             android:layout_width="100dip"
             android:layout_height="100dip"
                         />

   </LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<RelativeLayout
android:id="@+id/obrazek_pozadi0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

 <ImageView android:id="@+id/zaba_obrazek0"
android:src="@drawable/zaba_obrazek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
/>

</RelativeLayout>
</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<cz.zaba.Spojnice
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</LinearLayout>
</FrameLayout>
</code>```

答:
You can try this way -

```<code>ObjectAnimator.ofFloat(view, "translationX", 100f).apply {
    duration = 2000
    start()
}
</code>```

Note - view is your view where you want animation.

Body:
I have android translate Animation. I have an ImageView with random generated position (next1, next2). I am calling void every 3 seconds. It generates new position of the View and then make animation and move View to destination position. Translate animation has  AnimationListener implemented. When the animation finish,  I move View permanently to the new position (in OnAnimationEnd). My problem is that animation position does not correspond with setting layoutParams positions. When animation end, it makes jump to a new position, which is about 50-100 pixels far. I think the positions should be the same because I use same values (next1, next2) in both situations. Please can you show me the way to find sollution ?

 FrameLayout.LayoutParams pozice_motyl = (FrameLayout.LayoutParams)  pozadi_motyl.getLayoutParams();
            TranslateAnimation anim = new TranslateAnimation(Animation.ABSOLUTE,pozice_motyl.leftMargin, Animation.ABSOLUTE, next1, Animation.ABSOLUTE, pozice_motyl.topMargin, Animation.ABSOLUTE, next2);
            anim.setDuration(1000);
            anim.setFillAfter(true);
            anim.setFillEnabled(true);

            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(100, 100);

                    layoutParams.leftMargin = (int)(next1);
                    layoutParams.topMargin = (int)(next2);
                    pozadi_motyl.setLayoutParams(layoutParams);

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            pozadi_motyl.startAnimation(anim);

Here is XML layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/pozadi0"
    android:gravity="center_vertical"
    android:layout_gravity="center_vertical"
    android:background="@drawable/pozadi2"
    >

<LinearLayout
android:id="@+id/pozadi_motyl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

  <ImageView android:id="@+id/obrazek_motyl"
             android:src="@drawable/motyl"
             android:layout_width="100dip"
             android:layout_height="100dip"
                         />

   </LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<RelativeLayout
android:id="@+id/obrazek_pozadi0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

 <ImageView android:id="@+id/zaba_obrazek0"
android:src="@drawable/zaba_obrazek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
/>

</RelativeLayout>
</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<cz.zaba.Spojnice
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</LinearLayout>
</FrameLayout>

Body:
You can try this way -

ObjectAnimator.ofFloat(view, "translationX", 100f).apply {
    duration = 2000
    start()
}

Note - view is your view where you want animation.


来源: stackexchange

问:
SignedCms alternative in .NET Core
Does an alternative to System.Security.Cryptography.Pkcs.SignedCms class exist in .NET Core? Or do I have to dig into BouncyCastle, like they do in WinRT case? Is there an alternative of SignedCMS in WinRT?</p>

答:
FYI in case it helps. It seems that support for SignedCms and other essential .NET classes for S/MIME are available via this NUGET package:

```<code>System.Security.Cryptography.Pkcs
</code>```

I.e. before I added this NUGET package to my Visual Studio 2017 (VS2017) .NET Core project, I received these compilation errors:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'CmsRecipientCollection' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'X509IssuerSerial' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'EnvelopedCms' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'SignedCms' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'SignerInfoCollection' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'ContentInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'CmsRecipient' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'RecipientInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0103  The name 'SubjectIdentifierType' does not exist in the current context
Error   CS0246  The type or namespace name 'SignerInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS1579  foreach statement cannot operate on variables of type 'SignerInfoCollection' because 'SignerInfoCollection' does not contain a public instance definition for 'GetEnumerator'
Error   CS0246  The type or namespace name 'CmsSigner' could not be found (are you missing a using directive or an assembly reference?)
</code>```

After I added the NUGET package, I could compile successfully.

ContentLicense: CC BY-SA 3.0

Title: SignedCms alternative in .NET Core

Body:
FYI in case it helps. It seems that support for SignedCms and other essential .NET classes for S/MIME are available via this NUGET package:

System.Security.Cryptography.Pkcs

I.e. before I added this NUGET package to my Visual Studio 2017 (VS2017) .NET Core project, I received these compilation errors:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'CmsRecipientCollection' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'X509IssuerSerial' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'EnvelopedCms' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'SignedCms' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'SignerInfoCollection' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'ContentInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'CmsRecipient' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0246  The type or namespace name 'RecipientInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS0103  The name 'SubjectIdentifierType' does not exist in the current context
Error   CS0246  The type or namespace name 'SignerInfo' could not be found (are you missing a using directive or an assembly reference?)
Error   CS1579  foreach statement cannot operate on variables of type 'SignerInfoCollection' because 'SignerInfoCollection' does not contain a public instance definition for 'GetEnumerator'
Error   CS0246  The type or namespace name 'CmsSigner' could not be found (are you missing a using directive or an assembly reference?)

After I added the NUGET package, I could compile successfully.

ContentLicense: CC BY-SA 4.0


问:
How to generate a pseudorandom 32-byte string for use as a salt in a cryptographic hash function?
I am trying to code a password encryption function in C++ (Note: for educational purposes only. I won't actually be storing my passwords with it.) but I am not sure how to create a random 32-byte salt using a predefined characterset. How would I do this?

```<code>#include <random>
#include <iostream>

using namespace std;

void genSalt() {

    const char charset[] = {

        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "!£$%^&*():@~#'?/><.,|`¬¦"

    };

}
</code>```

The code should generate a random 32-byte string based on the defined character set 'charset'. I am not sure how to achieve this.

答:
First thing you want to watch out for is the storage of some of those characters in the source file. Depending on encoding, £, ¬, or ¦ could potentially be more than one byte, which can screw up your result; you should store those as hardcoded bytes if you want things to go smoothly regardless of encoding:

```<code>const char charset[] =
    "0123456789"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "!\xA3$%^&*():@~#'?/><.,|`\xAC\xA6";

// \xA3 = single-byte extended encoding for £
// \xAC = ¬
// \xA6 = ¦
</code>```

(And by smoothly, I mean using those characters in your salt is a bad idea regardless, as they might conflict with other encodings where the salt is used.)

As for generating password salt, I'm no cryptologist, but it seems a little bit iffy to me to use anything other than a cryptographically secure psuedorandom number generator. If it's just a C++ exercise, the builtin random generators will be fine. I've never actually used the C++11 PRNG functions so this is a neat exercise for me too.

You start by making a random_device and then a randomizer engine:

```<code>#include <random>
std::random_device my_random_device;
std::default_random_engine my_random_engine(my_random_device());
</code>```

There are different engines you can choose from for fine-tuning your random numbers, and default is an implementation defined selection (I assume that with this you can also easily plug in a cryptographically secure generator).

The random_device handles seeding automatically, whereas if you're using the older C-style rand function, you'd want to call srand with a seed (like the system time) to initialize it before generating anything.

To pick characters from your salt source, you select a distribution method, which you can get more details about here: https://en.cppreference.com/w/cpp/numeric/random

In this case, you want a uniform distribution across the set of salt characters:

```<code>std::uniform_int_distribution<int> random_number(0, sizeof(charset) - 1);
</code>```

Which you can call as random_number(my_random_engine) to get a number between 0 and the last character index (don't forget to minus 1 to skip the null terminator).

And then with that it's easy to sample the characters and build a string:

```<code>std::string salt;
salt.reserve( 32 );
for( int i = 0; i < 32; i++ ) {
    salt.push_back(charset[random_number(my_random_engine)]);
}
std::cout << "salt result: " << salt << std::endl;
</code>```

Working example: https://wandbox.org/permlink/mGd8pYP9Y3injuuG

One other thing I'd like to mention is the common pitfall of using % against a random number. For example, consider this test case using the older C-style rand() function:

```<code>int main() {
    // Seed randomizer
    srand( time(0) );

    // Print a random number between 0 and 1999
    int number = rand() % 2000;
    std::cout << number;
}
</code>```

Usually people don't care, because it's "random enough", but you aren't going to get uniform distribution with modulus (%). rand() generates a number between 0 and RAND_MAX, and you should instead scale the range returned to fit your desired range.

```<code>// Sample random number between 0 and 1999. (add 1 to rand max to make 2000 not slightly possible)
int number = rand() * 2000 / (RAND_MAX+1)
</code>```

Remember to pick an appropriate PRNG function to suit your needs as well, especially when looking for substantially difficult odds. If you're searching for 1 in 1 million, you may never find the result if the PRNG function doesn't uniformly cover the desired range.

Body:
I am trying to code a password encryption function in C++ (Note: for educational purposes only. I won't actually be storing my passwords with it.) but I am not sure how to create a random 32-byte salt using a predefined characterset. How would I do this?

#include <random>
#include <iostream>

using namespace std;

void genSalt() {

    const char charset[] = {

        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "!£$%^&*():@~#'?/><.,|`¬¦"

    };

}

The code should generate a random 32-byte string based on the defined character set 'charset'. I am not sure how to achieve this.

Body:
First thing you want to watch out for is the storage of some of those characters in the source file. Depending on encoding, £, ¬, or ¦ could potentially be more than one byte, which can screw up your result; you should store those as hardcoded bytes if you want things to go smoothly regardless of encoding:

const char charset[] =
    "0123456789"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "!\xA3$%^&*():@~#'?/><.,|`\xAC\xA6";

// \xA3 = single-byte extended encoding for £
// \xAC = ¬
// \xA6 = ¦

(And by smoothly, I mean using those characters in your salt is a bad idea regardless, as they might conflict with other encodings where the salt is used.)

As for generating password salt, I'm no cryptologist, but it seems a little bit iffy to me to use anything other than a cryptographically secure psuedorandom number generator. If it's just a C++ exercise, the builtin random generators will be fine. I've never actually used the C++11 PRNG functions so this is a neat exercise for me too.

You start by making a random_device and then a randomizer engine:

#include <random>
std::random_device my_random_device;
std::default_random_engine my_random_engine(my_random_device());

There are different engines you can choose from for fine-tuning your random numbers, and default is an implementation defined selection (I assume that with this you can also easily plug in a cryptographically secure generator).

The random_device handles seeding automatically, whereas if you're using the older C-style rand function, you'd want to call srand with a seed (like the system time) to initialize it before generating anything.

To pick characters from your salt source, you select a distribution method, which you can get more details about here: https://en.cppreference.com/w/cpp/numeric/random

In this case, you want a uniform distribution across the set of salt characters:

std::uniform_int_distribution<int> random_number(0, sizeof(charset) - 1);

Which you can call as random_number(my_random_engine) to get a number between 0 and the last character index (don't forget to minus 1 to skip the null terminator).

And then with that it's easy to sample the characters and build a string:

std::string salt;
salt.reserve( 32 );
for( int i = 0; i < 32; i++ ) {
    salt.push_back(charset[random_number(my_random_engine)]);
}
std::cout << "salt result: " << salt << std::endl;

Working example: https://wandbox.org/permlink/mGd8pYP9Y3injuuG

One other thing I'd like to mention is the common pitfall of using % against a random number. For example, consider this test case using the older C-style rand() function:

int main() {
    // Seed randomizer
    srand( time(0) );

    // Print a random number between 0 and 1999
    int number = rand() % 2000;
    std::cout << number;
}

Usually people don't care, because it's "random enough", but you aren't going to get uniform distribution with modulus (%). rand() generates a number between 0 and RAND_MAX, and you should instead scale the range returned to fit your desired range.

// Sample random number between 0 and 1999. (add 1 to rand max to make 2000 not slightly possible)
int number = rand() * 2000 / (RAND_MAX+1)

Remember to pick an appropriate PRNG function to suit your needs as well, especially when looking for substantially difficult odds. If you're searching for 1 in 1 million, you may never find the result if the PRNG function doesn't uniformly cover the desired range.


问:
javascript pass html input type id to function
Suppose I have a list of the following HTML elements with a Javascript event to copy the content of the HTML input type text into the clipboard:

```<code><input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>
</code>```

etc..

How do I copy the txt using javascript?

I am trying to tweak the code below but I can't figure out how to pass the HTML id to the javascript code. I know the getElementById() is not correct in that context and shouldn't be called. But I don't know how to carry the id value across into the Javascript function.

```<code><script>
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>
</code>```

Any help would be greatly appreciated.

Thank you

答: The error is that you use document.getElementById("myInput") instead of document.getElementById(myInput).

Body:
Suppose I have a list of the following HTML elements with a Javascript event to copy the content of the HTML input type text into the clipboard:

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

etc..

How do I copy the txt using javascript?

I am trying to tweak the code below but I can't figure out how to pass the HTML id to the javascript code. I know the getElementById() is not correct in that context and shouldn't be called. But I don't know how to carry the id value across into the Javascript function.

Any help would be greatly appreciated.

Thank you


问:
[Azure Policy]Apply tag and add the account info
When creating a resource group with Azure Policy, I would like to force account information such as user ID and email address as tags.

Sample-Apply tag and its default value

As a result of referring to, it was possible to tag a fixed word, but I do not know how to obtain the aforementioned account information dynamically.

If you know anyone, please teach me how.

Thank you.

答:
If the requirement is when creating / defining the policy:

You may obtain the account information dynamically by using Get-AzContext cmdlet. Note that user ID and email address might be assigned to its (Get-AzContext) properties like 'Account', 'Account.Id', 'Name', etc. So you may run below commands and check the output's to validate User ID, email address are assigned to some context properties in your environment and use them.

```<code>Get-AzContext | fl *

Get-AcContext | Select -ExpandProperty ExtendedProperties

$UserID = (Get-AzContext).Account.Id

$UserID = (Get-AzContext).Name
</code>```

And then provide the dynamically fetched User ID, email address to $policyparam variable (that is mentioned in deployment step of the tutorial you are following).

If the requirement is when applying the policy:

AFAIK this feature is currently unsupported / not possible via Azure policies. However, to accomplish requirement of tagging user ID and email address for very recently created resource groups, you may leverage related create events from the activity logs and then just have an automated way something like a function app to fetch those events and add required tags (with information like user ID, email address, etc.) to respective resource groups on the fly.

Body:
If the requirement is when creating / defining the policy:

You may obtain the account information dynamically by using Get-AzContext cmdlet. Note that user ID and email address might be assigned to its (Get-AzContext) properties like 'Account', 'Account.Id', 'Name', etc. So you may run below commands and check the output's to validate User ID, email address are assigned to some context properties in your environment and use them.

Get-AzContext | fl *

Get-AcContext | Select -ExpandProperty ExtendedProperties

$UserID = (Get-AzContext).Account.Id

$UserID = (Get-AzContext).Name

And then provide the dynamically fetched User ID, email address to $policyparam variable (that is mentioned in deployment step of the tutorial you are following).

If the requirement is when applying the policy:

AFAIK this feature is currently unsupported / not possible via Azure policies. However, to accomplish requirement of tagging user ID and email address for very recently created resource groups, you may leverage related create events from the activity logs and then just have an automated way something like a function app to fetch those events and add required tags (with information like user ID, email address, etc.) to respective resource groups on the fly.


问:
Update Dataframe column value based on other Dataframe column value
I have a pandas Dataframe which has a couple of columns.
I want to get the first 3 elements out of the Information Column based on a value in Protocol.

For example: I want the first 3 elements in Information IF the protocol is TCP.

Using below code I can separate the columns needed for my operation. But I have no clue how to adapt the next piece of code to this.

```<code>chunk[['Protocol', 'Information']] = chunk[['Protocol', 'Information']]
</code>```

EDIT:

I wish to update the values. Not separate them.

答:
You can use something like this:

```<code>import pandas

data = data = {'Name':['first', 'second', 'third', 'fourth'],
        'Age':[27, 27, 22, 32],
        'Address':['New York', 'ABC', 'XYZ', 'Nowhere'],
        'Qualification':['Msc', 'MA', 'MA', 'Phd']}

# Make a dataframe object
df = pandas.DataFrame(data)

# Your condition
# for example we want to get the rows with `Qualitication=='MA'
is_MA_qualified = df['Qualification'] == 'MA'

# Now to filter your data
MA_qualified = df[is_MA_qualified]

# You can use `head(n)` to get first three rows
first_three_MA_qualified = MA_qualified.head(3)

# And finally, to get any desired columns
first_three_MA_qualified[['Age','Address']]
</code>```

UPDATE:
to update cells, you can iterate over rows and then change the values of the cells that fulfill the condition:

...
for index, row in df.iterrows():
    if row['Age'] >= 18:
        df.at[index, 'Qualification'] = 'Verified'
```

Body:
I have a pandas Dataframe which has a couple of columns.
I want to get the first 3 elements out of the Information Column based on a value in Protocol.

For example: I want the first 3 elements in Information IF the protocol is TCP.

Using below code I can separate the columns needed for my operation. But I have no clue how to adapt the next piece of code to this.

chunk[['Protocol', 'Information']] = chunk[['Protocol', 'Information']]

EDIT:

I wish to update the values. Not separate them.

Body:
You can use something like this:

import pandas

data = data = {'Name':['first', 'second', 'third', 'fourth'],
        'Age':[27, 27, 22, 32],
        'Address':['New York', 'ABC', 'XYZ', 'Nowhere'],
        'Qualification':['Msc', 'MA', 'MA', 'Phd']}

# Make a dataframe object
df = pandas.DataFrame(data)

# Your condition
# for example we want to get the rows with `Qualitication=='MA'
is_MA_qualified = df['Qualification'] == 'MA'

# Now to filter your data
MA_qualified = df[is_MA_qualified]

# You can use `head(n)` to get first three rows
first_three_MA_qualified = MA_qualified.head(3)

# And finally, to get any desired columns
first_three_MA_qualified[['Age','Address']]

UPDATE:
to update cells, you can iterate over rows and then change the values of the cells that fulfill the condition:

...
for index, row in df.iterrows():
    if row['Age'] >= 18:
        df.at[index, 'Qualification'] = 'Verified'


问:
display error if mail function not working
I'm building an Email verification script and i'm using ajax so whenever the user fill in a false or an invalid email, an error bar with the error name will be displayed, And when the email is true and belongs to an active account, an email will be sent to the user with instructions and the error bar says email sent.
The problem is even the mail function isn't working, the error bar keeps saying email sent.
So i wan't some lines to detect if the email wasn't sent to show "email was not sent" in the error bar.

This is my php file :

```<code>    <?php

include '../../app/init.php';

        /* Clean email */
    $recover_email = $_POST['recover_email'];

       /* check if email is valid */
    if(!filter_var($recover_email, FILTER_VALIDATE_EMAIL)) {

        /* email not valid */
        echo 3;

        /* Check if email exist */
    } else if(Database::exists('user_id', 'users', ['email' => $recover_email])) {

        /* Define some variables */
        $user_id            = Database::simple_get('user_id', 'users', ['email' => $recover_email]);
        $lost_password_code = md5($recover_email + microtime());

        /* Update the current activation email */
        $database->query("UPDATE `users` SET `lost_password_code` = '{$lost_password_code}' WHERE `user_id` = {$user_id}");

        /* Send the email */
        sendmail($recover_email,  $settings->contact_email, $language->lost_password->email->title, sprintf($language->lost_password->email->content, $settings->url, $recover_email, $lost_password_code));

        /* email exist */
        echo true;

    } else if(!Database::exists('user_id', 'users', ['email' => $email])) {

        /* email not exist */
        echo false;
    }

?>
</code>```

This is my mail functions :

```<code>function send_mail($to, $from, $title, $message) {

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to, $title, $message, $headers);
}

function sendmail($to, $from, $title, $message) {
    global $settings;

    if(!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->isHTML(true);

        $mail->Host = gethostbyname('tls://'.$settings->smtp_host);
        $mail->Port = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body = $message;

        if (!$mail->send()) {
            send_mail($to, $from, $title, $message);
        }

    } else {
        send_mail($to, $from, $title, $message);
    }

}
</code>```

I only need some lines on the php file to return it as a response for the ajax file

答:
just use mail() in if condition and print the appropriate message in if and else block. it will solve the problem</p>

```<code>if(mail($to, $title, $message, $headers)){
//success message
}
else{
//error message
}
</code>```

Body:
I'm building an Email verification script and i'm using ajax so whenever the user fill in a false or an invalid email, an error bar with the error name will be displayed, And when the email is true and belongs to an active account, an email will be sent to the user with instructions and the error bar says email sent.
The problem is even the mail function isn't working, the error bar keeps saying email sent.
So i wan't some lines to detect if the email wasn't sent to show "email was not sent" in the error bar.

This is my php file :

    <?php

include '../../app/init.php';

        /* Clean email */
    $recover_email = $_POST['recover_email'];

       /* check if email is valid */
    if(!filter_var($recover_email, FILTER_VALIDATE_EMAIL)) {

        /* email not valid */
        echo 3;

        /* Check if email exist */
    } else if(Database::exists('user_id', 'users', ['email' => $recover_email])) {

        /* Define some variables */
        $user_id            = Database::simple_get('user_id', 'users', ['email' => $recover_email]);
        $lost_password_code = md5($recover_email + microtime());

        /* Update the current activation email */
        $database->query("UPDATE `users` SET `lost_password_code` = '{$lost_password_code}' WHERE `user_id` = {$user_id}");

        /* Send the email */
        sendmail($recover_email,  $settings->contact_email, $language->lost_password->email->title, sprintf($language->lost_password->email->content, $settings->url, $recover_email, $lost_password_code));

        /* email exist */
        echo true;

    } else if(!Database::exists('user_id', 'users', ['email' => $email])) {

        /* email not exist */
        echo false;
    }

?>

This is my mail functions :

function send_mail($to, $from, $title, $message) {

    $headers = "From: " . strip_tags($from) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to, $title, $message, $headers);
}

function sendmail($to, $from, $title, $message) {
    global $settings;

    if(!empty($settings->smtp_host) && !empty($settings->smtp_port) && !empty($settings->smtp_user) && !empty($settings->smtp_pass)) {

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->isHTML(true);

        $mail->Host = gethostbyname('tls://'.$settings->smtp_host);
        $mail->Port = $settings->smtp_port;
        $mail->Username = $settings->smtp_user;
        $mail->Password = $settings->smtp_pass;

        $mail->setFrom($from, $settings->title);
        $mail->addReplyTo($from, $settings->title);
        $mail->addAddress($to);
        $mail->Subject = $title;
        $mail->Body = $message;

        if (!$mail->send()) {
            send_mail($to, $from, $title, $message);
        }

    } else {
        send_mail($to, $from, $title, $message);
    }

}

I only need some lines on the php file to return it as a response for the ajax file

Body:
just use mail() in if condition and print the appropriate message in if and else block. it will solve the problem

if(mail($to, $title, $message, $headers)){
//success message
}
else{
//error message
}


问:
how to set UserControl Screen at center of page in wpf
i need to keep usercontrol page at center location of page
to keep window form at center thr is option in property WindowStartuplocation center
but for usercontrol i m not getting</p>

答:
your UserControl has to be in an other control (Window, Grid, Canvas, etc...), so set the postion of this control at center location and you will be good !

Example :

```<code> <Canvas>
       <YourUserControl Canvas.Top="200" Canvas.Left ="400"></YourUserControl>
 </Canvas>
</code>```

Body:
your UserControl has to be in an other control (Window, Grid, Canvas, etc...), so set the postion of this control at center location and you will be good !

Example :

 <Canvas>
       <YourUserControl Canvas.Top="200" Canvas.Left ="400"></YourUserControl>
 </Canvas>


问:
How to convert array of integers into an integer in C?
How can I convert an array of 6 integers into a single integer.  Example provided below of what I want to do.

Array: {0, 1, 2, 3, 4, 5, 6}

Integer:  123456

Thank you!

答:
try this one:</p>

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

int main()
{
    int arr[] = {1, 2, 2, 43, 4, 27};
    int size = sizeof(arr)/sizeof(arr[0]);
    int n = 0;
    int number  = 0;
    int val  = 0;
    while(n <size)
    {
        val = arr[n];
        while(val!= 0)
        {
            val = val/10;
            number = number*10;
        }
        number = number + arr[n];
        n++;
    }
    printf("%d", number);
    return 0;
}
</code>```

Body:
try this one:

#include <stdio.h>
#include <math.h>

int main()
{
    int arr[] = {1, 2, 2, 43, 4, 27};
    int size = sizeof(arr)/sizeof(arr[0]);
    int n = 0;
    int number  = 0;
    int val  = 0;
    while(n <size)
    {
        val = arr[n];
        while(val!= 0)
        {
            val = val/10;
            number = number*10;
        }
        number = number + arr[n];
        n++;
    }
    printf("%d", number);
    return 0;
}


问:
Generic WCF Routing/Forwarding/Proxy Server
Is it possible to create a "generic" as in "adaptable" routing service, which will NOT have any public methods to call. Instead, you'd be able to call any command, which would then be mapped in the service and will pass it to appropriate end point with simple message transformation where required.
It may be hard to understand and idea might seem a bit crazy (it came from a colleague of mine), but it's clearer if you look at the example:

similar to what's described in this article, only difference is that our service should not have a "SubmitTimeSheet" public method, in fact it should have no public methods to call. We'd have to "intercept" an incoming call on a much lower level before it returns "Method Not Found" error.

Is this at all possible? The reason for this is obvious: possibility of adding new clients without having to change the code. All we'd have to do is to add a new mapping entry in some sort of config file or even database, e.g.

```<code><Client address="newClientAddress" method="DoAnything" transformation="NewClientDoAnything.xslt" endPoint="endPointClientAddress" endPointMethod="endPointClientDoAnything" />
</code>```

答:
They have already done it in Nirvana. But it is very expensive.

This is not possible in WCF unless you define your contract as a very loose, fit-for-all contract which takes a message and returns a message. By doing this, you will los all the goodness (although not huge goodness in WCF) of WCF.

Body:
Is it possible to create a "generic" as in "adaptable" routing service, which will NOT have any public methods to call. Instead, you'd be able to call any command, which would then be mapped in the service and will pass it to appropriate end point with simple message transformation where required.
It may be hard to understand and idea might seem a bit crazy (it came from a colleague of mine), but it's clearer if you look at the example:

similar to what's described in this article, only difference is that our service should not have a "SubmitTimeSheet" public method, in fact it should have no public methods to call. We'd have to "intercept" an incoming call on a much lower level before it returns "Method Not Found" error.

Is this at all possible? The reason for this is obvious: possibility of adding new clients without having to change the code. All we'd have to do is to add a new mapping entry in some sort of config file or even database, e.g.

<Client address="newClientAddress" method="DoAnything" transformation="NewClientDoAnything.xslt" endPoint="endPointClientAddress" endPointMethod="endPointClientDoAnything" />


问:
Is it possible to update a For End argument while inside it?
I wanted to change my For "End" argument while inside the For.

For instance:

```<code>ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i
</code>```

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

答:
I have no idea why you need to increase the ending, and why you cannot use other options as Do...Loop, but this migh work for you. Try to adapt it to your needs:

```<code>Dim ForEnd As Byte 'Limit or FOR...NEXT
Dim i As Byte 'Counter of FOR...NEXT
Dim XX As Byte 'It will store the last value of i when we restart the FOR...NEXT
Dim Something As String

ForEnd = 3
XX = 1 'First value of i

For_Start:

For i = XX To ForEnd Step 1
    If Something = "TRUE" Then
        ForEnd = ForEnd + 1
        XX = i + 1
        GoTo For_Start
    End If

Next i
</code>```

You handle with another variable the last position of your loop, and restart it from there with a GoTo

Body:
I wanted to change my For "End" argument while inside the For.

For instance:

ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

Body:
I have no idea why you need to increase the ending, and why you cannot use other options as Do...Loop, but this migh work for you. Try to adapt it to your needs:

Dim ForEnd As Byte 'Limit or FOR...NEXT
Dim i As Byte 'Counter of FOR...NEXT
Dim XX As Byte 'It will store the last value of i when we restart the FOR...NEXT
Dim Something As String

ForEnd = 3
XX = 1 'First value of i

For_Start:

For i = XX To ForEnd Step 1
    If Something = "TRUE" Then
        ForEnd = ForEnd + 1
        XX = i + 1
        GoTo For_Start
    End If

Next i

You handle with another variable the last position of your loop, and restart it from there with a GoTo


问:
How to structure/manipulate data before a POST or after a GET request using Effects
I'm setting up a new project using @NgRx and it's going fairly well.

The only problem right now is that I structured my store in a way that's better for the front-end, removing nests and making everything simpler but now I need to make requests to my API (get/post) which requires inputs/returns in a specific format.

How am I supposed to deal with this kind of data?

答:
In the functions/services that make the HTTP requests.

Your application state has a model, if your API requests another state, then it's ouside of your application scope : you just have to make mappers that will convert your application state to the model expected by the server.

You can either do it in the related services, in a specific converting service, or in util classes/functions.

The reason is that if, tommorow, you create another app that requests to the same server, then by copy/pasting the services/utils, you won't have to change anything.


问:
Django, browser display filename instead of the picture
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

```<code><img src="{{Object.picture.url}}"/>
</code>```

On template I have tried:

1

```<code><img src="{{ posts.title_picture.url }}"/>
</code>```

2

```<code><img src="{{title_picture.url}}"/>
</code>```

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

```<code>class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)
</code>```

view:

```<code>class IndexView(ListView):
    model = Post
    context_object_name = 'posts'
</code>```

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

and added the following

```<code>urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

</code>```

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

答:
You must use models.ImageField() instead of  models.FileField().
And must install 'Pillow' package with pip.

Body:
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

On template I have tried:

1

2

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)

view:

class IndexView(ListView):
    model = Post
    context_object_name = 'posts'

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and added the following

urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.


问:
How to debug a class library that is not a dependency of the main C# application (in Visual Studio)?
I have a solution where I load some dlls at runtime with Assembly.LoadFile. Because these dlls can come from multiple sources at any time, I cannot add them as a dependency to the main application. It seems that Visual Studio won't load pdb files for dlls that are not marked as a dependency.

I don't want to add each dll I'm debugging to the dependencies just to debug them. Is there a way to manually load symbols for these external dlls?

答: Use reflection. Use methods without creating objects. </p>


问:
How to make Dllimport correctly in c#?
ive had some problems building a correct .dll from a c++-project to my c#-project.
I played around with the c++-project-properties and got a .dll file which i can add and refer to in my c# web-project. I use Dllimport to make a function call to the .dll like this:

```<code>[DllImport("Filename.dll", CharSet = CharSet.Ansi)]
static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,
                             int srcLen,
                             [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,
                             int dstLen)
</code>```

The c++ function header is:

```<code>__declspec(dllimport) void Function1(unsigned char *src,
                     unsigned long srclen,
                     unsigned char *dst,
                     unsigned long dstlen);
</code>```

Im calling Function1 in c# with this:

```<code>string strSrc = "Something";
StringBuilder strDest = new StringBuilder(kryptlen-1);
int l = strSrc.Length();
Function1(strSrc, l, strDest, l);
</code>```

No exceptions or errors are occuring, though im not getting the output im expecting. The function is a decrypting method that takes an encrypted string(src) and returns the decrypted version of this (dst).

Is it the way ive generated the .dll file or is it the wrong way im calling the function? Im running out of ideas ive tried most combinations.

Thanks in advice!

答:
Where'd UnmanagedType.LPWStr come from?  There are no wide strings in the C++ declaration.  You're also passing the source length twice, while the variable names suggest you need the source length and the destination buffer capacity.

If src is encrypted data as you say, the correct p/invoke signature is probably:

```<code>[DllImport("Filename.dll", CallingConvention = CallingConvention.CDecl)]
static extern void Function1(byte[] src,
                             UInt32 srcLen,
                             [MarshalAs(UnmanagedType.LPStr)] StringBuilder dst,
                             UInt32 dstLen)
</code>```

Trying to force binary data into a Unicode string is a losing proposition.

Title: How to make Dllimport correctly in c#?

Body:
ive had some problems building a correct .dll from a c++-project to my c#-project.
I played around with the c++-project-properties and got a .dll file which i can add and refer to in my c# web-project. I use Dllimport to make a function call to the .dll like this:

[DllImport("Filename.dll", CharSet = CharSet.Ansi)]
static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,
                             int srcLen,
                             [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,
                             int dstLen)

The c++ function header is:

__declspec(dllimport) void Function1(unsigned char *src,
                     unsigned long srclen,
                     unsigned char *dst,
                     unsigned long dstlen);

Im calling Function1 in c# with this:

string strSrc = "Something";
StringBuilder strDest = new StringBuilder(kryptlen-1);
int l = strSrc.Length();
Function1(strSrc, l, strDest, l);

No exceptions or errors are occuring, though im not getting the output im expecting. The function is a decrypting method that takes an encrypted string(src) and returns the decrypted version of this (dst).

Is it the way ive generated the .dll file or is it the wrong way im calling the function? Im running out of ideas ive tried most combinations.

Thanks in advice!

Body:
Where'd UnmanagedType.LPWStr come from?  There are no wide strings in the C++ declaration.  You're also passing the source length twice, while the variable names suggest you need the source length and the destination buffer capacity.

If src is encrypted data as you say, the correct p/invoke signature is probably:

[DllImport("Filename.dll", CallingConvention = CallingConvention.CDecl)]
static extern void Function1(byte[] src,
                             UInt32 srcLen,
                             [MarshalAs(UnmanagedType.LPStr)] StringBuilder dst,
                             UInt32 dstLen)

Trying to force binary data into a Unicode string is a losing proposition.


问:
How can I set an entire NGRX store and then trigger all reducers?
How can I?

Get entire NGRX store data

Set entire NGRX store data

Trigger all reducers

Background:

I have an angular application that has many components tightly coupled to an NGRX store.

I've reused these components for a flattened print layout of some of the information in the application. I use headless chrome to print the application to a pdf. Since the headless chrome is a different user-agent than the print-user's browser there is no data.

I initially solved this problem by posting over some of the NGRX store and having the headless chrome replace it in the store. However as the print view has expanded the amount of data needed from the store has grown to be unmanageable.

I would like to take the entire store data, then reinsert it into the other user-agent store, then trigger all reducers to ensure components update.

I already know how to get all of the store data. I could use some help on putting it back into the store. What I need most is how to trigger all reducers without writing hundreds of dispatch statements.

答:
Keeping browser tabs in sync using localStorage, NgRx, and RxJS can help you here.

Since you already solved the first problem:

A meta-reducer is the best fit here:

```<code>// set state based on local storage
export function persistStateReducer(_reducer: ActionReducer<State>) {
  const localStorageKey = '__groceries';
  return (state: State | undefined, action: Action) => {
    if (state === undefined) {
      const persisted = localStorage.getItem(localStorageKey);
      return persisted ? JSON.parse(persisted) : _reducer(state, action);
    }

    const nextState = _reducer(state, action);
    localStorage.setItem(localStorageKey, JSON.stringify(nextState));
    return nextState;
  };
}

// reset the whole state via the action's payload
export function updateStateReducer(_reducer: ActionReducer<State>) {
  return (state: State | undefined, action: Action) => {
    if (action.type === 'UPDATE_GROCERIES_STATE') {
      return (<any>action).payload.newState;
    }

    return _reducer(state, action);
  };
}
</code>```

When you dispatch an action all of the reducers will be triggered

Body:
Keeping browser tabs in sync using localStorage, NgRx, and RxJS can help you here.

Since you already solved the first problem:

A meta-reducer is the best fit here:

// set state based on local storage
export function persistStateReducer(_reducer: ActionReducer<State>) {
  const localStorageKey = '__groceries';
  return (state: State | undefined, action: Action) => {
    if (state === undefined) {
      const persisted = localStorage.getItem(localStorageKey);
      return persisted ? JSON.parse(persisted) : _reducer(state, action);
    }

    const nextState = _reducer(state, action);
    localStorage.setItem(localStorageKey, JSON.stringify(nextState));
    return nextState;
  };
}

// reset the whole state via the action's payload
export function updateStateReducer(_reducer: ActionReducer<State>) {
  return (state: State | undefined, action: Action) => {
    if (action.type === 'UPDATE_GROCERIES_STATE') {
      return (<any>action).payload.newState;
    }

    return _reducer(state, action);
  };
}

When you dispatch an action all of the reducers will be triggered


问:
Set permissions for different namespaces in Azure DevOps using Rest API
How can I use RestAPI to set permissions for Build definitions, Release definitions, git repo and team securities? When I was using TFS, I was able to do this using Tfsssecurity.exe tool.

Edited.
For example, I am trying to modify the project permissions of Contributors group. like Allow Contributors to rename team project etc.

enter image description here

答:
There isn’t the REST API to change permission of release definition and git repo. Other contributors submit a user voice that you can vote Set version control permissions by REST API

For details,please refer to these links:

VSTS REST API to change security permissions on Release definition or Release definition environment

Use VSTS Rest API to set git repo permissions

Hope this helps.


问:
UnitTest on WebAPI controller with Windows Authentication
I've an api with few methods in it. I need to authenticate user with Windows Authentication before it hits any of the controller methods. To achieve this, I've written a private method to get the UserIdentity and assign it to  a private bool variable.

Each of the controller methods will first check the bool to verify the user and if it fails, will throw 401 back to the front end.

Whilst writing unit test case to the controller methods, I'm not sure how to mock the UserIdentity or should I update the controller in a way to allow the testing of UserIdentity

Controller :

```<code>public class DefaultController : ApiController
{
  private bool isUsrAuthenticated;

  public DefaultController()
  {
    AuthenticateUser();
  }

  private void AuthenticateUser()
  {
    isUsrAuthenticated = User.Identity.IsAuthenticated;
  }

  [HttpGet]
  public IHttpActionResult GetProducts()
  {
    if (isUsrAuthenticated) { // do something }
    else { // throw 401 }
  }

  [HttpPost]
  public IHttpActionResult Update()
  {
    if (isUsrAuthenticated) { // do something }
    else { // throw 401 }
  }
}
</code>```

The Unit Test results always return 401.

答:
At run-time the ApiController.User property is set well after the constructor of the controller is invoked. That would mean that your current flow of calling it in the constructor like

```<code>public DefaultController() {
    AuthenticateUser();
}
</code>```

is flawed and will not provide the expected behavior.

Lets fix the code first, then look at the unit test.

Use a property instead like

```<code>private bool IsUserAuthenticated {
    get {
        return User.Identity.IsAuthenticated;
    }
}
</code>```

and refactor the code accordingly

```<code>public class DefaultController : ApiController {

    private bool IsUserAuthenticated {
        get {
            return User.Identity.IsAuthenticated;
        }
    }

    [HttpGet]
    public IHttpActionResult GetProducts() {
        if (IsUserAuthenticated) { // do something }
        else { // throw 401 }
    }

    [HttpPost]
    public IHttpActionResult Update() {
        if (IsUserAuthenticated) { // do something }
        else { // throw 401 }
    }

    //...

}
</code>```

Now, for testing the ApiController, the User property can be set while arranging the unit test in order for the test to be exercised as expected

For example

```<code>[TestMethod()]
public void DefaultController_Should_GetProducts() {
    //Arrange
    var username = "name_here";
    var userId = 2;

    var identity = new GenericIdentity(username, "");
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString()));
    identity.AddClaim(new Claim(ClaimTypes.Name, username));

    var principal = new GenericPrincipal(identity, roles: new string[] { });
    var user = new ClaimsPrincipal(principal);

    var controller = new DefaultController() {
        User = user //<-- Set the User on the controller directly
    };

    //Act
    var actionResult = controller.GetProducts();

    //Assert
    //...
}
</code>```

Body:
I've an api with few methods in it. I need to authenticate user with Windows Authentication before it hits any of the controller methods. To achieve this, I've written a private method to get the UserIdentity and assign it to  a private bool variable.

Each of the controller methods will first check the bool to verify the user and if it fails, will throw 401 back to the front end.

Whilst writing unit test case to the controller methods, I'm not sure how to mock the UserIdentity or should I update the controller in a way to allow the testing of UserIdentity

Controller :

public class DefaultController : ApiController
{
  private bool isUsrAuthenticated;

  public DefaultController()
  {
    AuthenticateUser();
  }

  private void AuthenticateUser()
  {
    isUsrAuthenticated = User.Identity.IsAuthenticated;
  }

  [HttpGet]
  public IHttpActionResult GetProducts()
  {
    if (isUsrAuthenticated) { // do something }
    else { // throw 401 }
  }

  [HttpPost]
  public IHttpActionResult Update()
  {
    if (isUsrAuthenticated) { // do something }
    else { // throw 401 }
  }
}

The Unit Test results always return 401.

Body:
At run-time the ApiController.User property is set well after the constructor of the controller is invoked. That would mean that your current flow of calling it in the constructor like

public DefaultController() {
    AuthenticateUser();
}

is flawed and will not provide the expected behavior.

Lets fix the code first, then look at the unit test.

Use a property instead like

private bool IsUserAuthenticated {
    get {
        return User.Identity.IsAuthenticated;
    }
}

and refactor the code accordingly

public class DefaultController : ApiController {

    private bool IsUserAuthenticated {
        get {
            return User.Identity.IsAuthenticated;
        }
    }

    [HttpGet]
    public IHttpActionResult GetProducts() {
        if (IsUserAuthenticated) { // do something }
        else { // throw 401 }
    }

    [HttpPost]
    public IHttpActionResult Update() {
        if (IsUserAuthenticated) { // do something }
        else { // throw 401 }
    }

    //...

}

Now, for testing the ApiController, the User property can be set while arranging the unit test in order for the test to be exercised as expected

For example

[TestMethod()]
public void DefaultController_Should_GetProducts() {
    //Arrange
    var username = "name_here";
    var userId = 2;

    var identity = new GenericIdentity(username, "");
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString()));
    identity.AddClaim(new Claim(ClaimTypes.Name, username));

    var principal = new GenericPrincipal(identity, roles: new string[] { });
    var user = new ClaimsPrincipal(principal);

    var controller = new DefaultController() {
        User = user //<-- Set the User on the controller directly
    };

    //Act
    var actionResult = controller.GetProducts();

    //Assert
    //...
}


答:
As mentioned by Olff, replace the for-loop by a while-loop:

```<code>ForEnd = 3
i = 1

while i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Wend
</code>```

Be very careful not ending up in an infinite loop! (Something needs to be different than "TRUE" regularly)

Another way to go (a more modern approach) is using the Do..Loop approach:

```<code>ForEnd = 3
i = 1

Do While i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Loop
</code>```

Title: Is it possible to update a For End argument while inside it?

Body:
As mentioned by Olff, replace the for-loop by a while-loop:

ForEnd = 3
i = 1

while i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Wend

Be very careful not ending up in an infinite loop! (Something needs to be different than "TRUE" regularly)

Another way to go (a more modern approach) is using the Do..Loop approach:

ForEnd = 3
i = 1

Do While i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Loop


问:
WPF ListView control is populated but invisible
I have a ListView, populated with ItemsSource pointing to a list of login histories, so that I can choose from previous successful logins instead of having to type user, host, etc. over. This seemed to be working fine, but for some reason now the databinding is working fine but the items in the control are invisible. I can tell the control is being populated correctly because "ghosts" of the items are available and highlight when I mouseover them, in the correct number as in my ItemsSource,  and they are bound correctly - for instance if my ItemsSource has LoginA, LoginQ, and LoginZ and click on the second 'invisible' item, LoginQ happens. I've tried messing with opacity, changing where ItemsSource is bound (after/before login dialog appears, etc). with no joy. Compared to an older working version I can't see anything that appears to be relevant. Hints, suggestions, and catcalls welcome.....</p>

答:
Here is the class for my ItemsSource: List, and the XAML which references it.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   public class LoginHistory
    {
        public string user;
        public string host;
        public string company;
        blah, blah, blah.........
}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

```<code>            <Border Name="mask" Opacity="0.8"  Background="White" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" CornerRadius="0,0,0,10"/>
            <ListView Background="White" BorderThickness="0" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
                      IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Stretch"
                      x:Name="HistoryListView" VerticalAlignment="Stretch" Width="Auto"
                      Height="Auto" FontSize="14" SelectionMode="Single"
                      SelectionChanged="HistoryListView_SelectionChanged">
                <ListView.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </ListView.OpacityMask>
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListViewItem}">
                        <Setter Property="Height" Value="40"/>
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.View>
                    <!--
                    <GridView ColumnHeaderTemplate="{StaticResource HeaderTemplateNoArrow}" AllowsColumnReorder="True">
                        -->
</code>```

                                User

```<code>                        <GridViewColumn DisplayMemberBinding="{Binding Path=company}">
                            <GridViewColumnHeader>Company</GridViewColumnHeader>
                        </GridViewColumn>

                        <GridViewColumn DisplayMemberBinding="{Binding Path=host}">
                            <GridViewColumnHeader>Host</GridViewColumnHeader>
                        </GridViewColumn>

                    </GridView>
                </ListView.View>
            </ListView>
            <Border BorderThickness="1" Margin="0" BorderBrush="Gray" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" CornerRadius="0,0,0,10">
            </Border>
</code>```

Body:
Here is the class for my ItemsSource: List, and the XAML which references it.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   public class LoginHistory
    {
        public string user;
        public string host;
        public string company;
        blah, blah, blah.........
}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            <Border Name="mask" Opacity="0.8"  Background="White" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" CornerRadius="0,0,0,10"/>
            <ListView Background="White" BorderThickness="0" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
                      IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Stretch"
                      x:Name="HistoryListView" VerticalAlignment="Stretch" Width="Auto"
                      Height="Auto" FontSize="14" SelectionMode="Single"
                      SelectionChanged="HistoryListView_SelectionChanged">
                <ListView.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </ListView.OpacityMask>
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListViewItem}">
                        <Setter Property="Height" Value="40"/>
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.View>
                    <!--
                    <GridView ColumnHeaderTemplate="{StaticResource HeaderTemplateNoArrow}" AllowsColumnReorder="True">
                        -->

                                User

                        <GridViewColumn DisplayMemberBinding="{Binding Path=company}">
                            <GridViewColumnHeader>Company</GridViewColumnHeader>
                        </GridViewColumn>

                        <GridViewColumn DisplayMemberBinding="{Binding Path=host}">
                            <GridViewColumnHeader>Host</GridViewColumnHeader>
                        </GridViewColumn>

                    </GridView>
                </ListView.View>
            </ListView>
            <Border BorderThickness="1" Margin="0" BorderBrush="Gray" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" CornerRadius="0,0,0,10">
            </Border>


问:
How to calculate an 0-1 certainty score for DecisionTreeClassifier?
Dataset
0-9 columns: float features (parameters of a product)
10 column: int labels (products)

Goal

Calculate an 0-1 classification certainty score for the labels (this is what my current code should do)

Calculate the same certainty score for each “product_name”(300 columns) at each rows(22'000)

ERROR I use sklearn.tree.DecisionTreeClassifier.
I am trying to use "predict_proba" but it gives an error.

Python CODE

```<code>data_train = pd.read_csv('data.csv')
features = data_train.columns[:-1]
labels = data_train.columns[-1]
x_features = data_train[features]
x_label = data_train[labels]
X_train, X_test, y_train, y_test = train_test_split(x_features, x_label, random_state=0)
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

clf = DecisionTreeClassifier(max_depth=3).fit(X_train, y_train)
class_probabilitiesDec = clf.predict_proba(y_train)
#ERORR: ValueError: Number of features of the model must match the input. Model n_features is 10 and input n_features is 16722

print('Decision Tree Classification Accuracy Training Score (max_depth=3): {:.2f}'.format(clf.score(X_train, y_train)*100) + ('%'))
print('Decision Tree Classification Accuracy Test Score (max_depth=3): {:.2f}'.format(clf.score(X_test, y_test)*100) + ('%'))

print(class_probabilitiesDec[:10])
# if I use X_tranin than it jsut prints out a buch of 41 element vectors: [[ 0.00490808  0.00765327  0.01123035  0.00332751  0.00665502  0.00357707
   0.05182597  0.03169453  0.04267532  0.02761833  0.01988187  0.01281091
   0.02936528  0.03934781  0.02329257  0.02961484  0.0353548   0.02503951
   0.03577073  0.04700108  0.07661592  0.04433907  0.03019715  0.02196157
   0.0108976   0.0074869   0.0291989   0.03951418  0.01372598  0.0176358
   0.02345895  0.0169703   0.02487314  0.01813493  0.0482489   0.01988187
   0.03252641  0.01572249  0.01455786  0.00457533  0.00083188]
 [....

</code>```

FEATURES (COLUMNS)

(last columns are the labels)
0   1   1   1   1.0 1462293561  1462293561  0   0   0.0 0.0 1
1   2   2   2   8.0 1460211580  1461091152  1   1   0.0 0.0 2
2   3   3   3   1.0 1469869039  1470560880  1   1   0.0 0.0 3
3   4   4   4   1.0 1461482675  1461482675  0   0   0.0 0.0 4
4   5   5   5   5.0 1462173043  1462386863  1   1   0.0 0.0 5

CLASSES COLUMNS (300 COLUMNS OF ITEMS)

HEADER ROW: apple gameboy battery ....
SCORE in 1st row: 0.763 0.346 0.345  ....
SCORE in 2nd row: 0.256 0.732 0.935 ....

ex.: of similar scores used when someone image classify cat VS. dog and the classification gives confidence scores.

答:
You cannot predict the probability of your labels.

predict_proba predicts the probability for each label from your X Data, thus:

```<code>class_probabilitiesDec = clf.predict_proba(X_test)
</code>```

What you postet as "when i use X_train":

```<code>[[ 0.00490808  0.00765327  0.01123035  0.00332751  0.00665502  0.00357707
   0.05182597  0.03169453  0.04267532  0.02761833  0.01988187  0.01281091
   0.02936528  0.03934781  0.02329257  0.02961484  0.0353548   0.02503951
   0.03577073  0.04700108  0.07661592  0.04433907  0.03019715  0.02196157
   0.0108976   0.0074869   0.0291989   0.03951418  0.01372598  0.0176358
   0.02345895  0.0169703   0.02487314  0.01813493  0.0482489   0.01988187
   0.03252641  0.01572249  0.01455786  0.00457533  0.00083188]
</code>```

Is a list of the probability to be true for every possible label.

EDIT

After reading your comments predict proba is exactly what you want.

Lets make an example. In the following code we have a classifier with 3 classes: either 11, 12 or 13.

If the input is 1 the classifier should predict 11

If the input is 2 the classifier should predict 12

...

If the input is 7 the classifier should predict 13

```<code>clf = DecisionTreeClassifier()
clf.fit([[1],[2],[3],[4],[5],[6],[7]], [[11],[12],[13],[13],[12],[11],[13]])
</code>```

now if you have test data with a single row e.g. 5 than the classifier should predict 12. So lets try that.

```<code>clf.predict([[5]])
</code>```

And voila: the result is array([12])

if we want a probability then predict proba is the way to go:

```<code>clf.predict_proba([[5]])
</code>```

and we get [array([0., 1., 0.])]

In that case the array [0., 1., 0.] means :

0% probability for class 11

100% probability for class 12

0% probability for class 13

If i'm correct thats exactly what you want.
You can even map that to the names of your classes with:

```<code>probabilities = clf.predict_proba([[5]])[0]
{clf.classes_[i] : probabilities[i] for i in range(len(probabilities))}
</code>```

which gives you a dictionary with probabilities for class names:

```<code>{11: 0.0, 12: 1.0, 13: 0.0}
</code>```

Now in your case you have way more classes than only [11,12,13] so the array gets longer. And for every row in your dataset predict_proba creates an array, so for more than a single row of data your output becomes a matrix.

Body:
Dataset
0-9 columns: float features (parameters of a product)
10 column: int labels (products)

Goal

Calculate an 0-1 classification certainty score for the labels (this is what my current code should do)

Calculate the same certainty score for each “product_name”(300 columns) at each rows(22'000)

ERROR I use sklearn.tree.DecisionTreeClassifier.
I am trying to use "predict_proba" but it gives an error.

Python CODE

data_train = pd.read_csv('data.csv')
features = data_train.columns[:-1]
labels = data_train.columns[-1]
x_features = data_train[features]
x_label = data_train[labels]
X_train, X_test, y_train, y_test = train_test_split(x_features, x_label, random_state=0)
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

clf = DecisionTreeClassifier(max_depth=3).fit(X_train, y_train)
class_probabilitiesDec = clf.predict_proba(y_train)
#ERORR: ValueError: Number of features of the model must match the input. Model n_features is 10 and input n_features is 16722

print('Decision Tree Classification Accuracy Training Score (max_depth=3): {:.2f}'.format(clf.score(X_train, y_train)*100) + ('%'))
print('Decision Tree Classification Accuracy Test Score (max_depth=3): {:.2f}'.format(clf.score(X_test, y_test)*100) + ('%'))

print(class_probabilitiesDec[:10])
# if I use X_tranin than it jsut prints out a buch of 41 element vectors: [[ 0.00490808  0.00765327  0.01123035  0.00332751  0.00665502  0.00357707
   0.05182597  0.03169453  0.04267532  0.02761833  0.01988187  0.01281091
   0.02936528  0.03934781  0.02329257  0.02961484  0.0353548   0.02503951
   0.03577073  0.04700108  0.07661592  0.04433907  0.03019715  0.02196157
   0.0108976   0.0074869   0.0291989   0.03951418  0.01372598  0.0176358
   0.02345895  0.0169703   0.02487314  0.01813493  0.0482489   0.01988187
   0.03252641  0.01572249  0.01455786  0.00457533  0.00083188]
 [....

FEATURES (COLUMNS)

(last columns are the labels)
0   1   1   1   1.0 1462293561  1462293561  0   0   0.0 0.0 1
1   2   2   2   8.0 1460211580  1461091152  1   1   0.0 0.0 2
2   3   3   3   1.0 1469869039  1470560880  1   1   0.0 0.0 3
3   4   4   4   1.0 1461482675  1461482675  0   0   0.0 0.0 4
4   5   5   5   5.0 1462173043  1462386863  1   1   0.0 0.0 5

CLASSES COLUMNS (300 COLUMNS OF ITEMS)

HEADER ROW: apple gameboy battery ....
SCORE in 1st row: 0.763 0.346 0.345  ....
SCORE in 2nd row: 0.256 0.732 0.935 ....

ex.: of similar scores used when someone image classify cat VS. dog and the classification gives confidence scores.

Body:
You cannot predict the probability of your labels.

predict_proba predicts the probability for each label from your X Data, thus:

class_probabilitiesDec = clf.predict_proba(X_test)

What you postet as "when i use X_train":

[[ 0.00490808  0.00765327  0.01123035  0.00332751  0.00665502  0.00357707
   0.05182597  0.03169453  0.04267532  0.02761833  0.01988187  0.01281091
   0.02936528  0.03934781  0.02329257  0.02961484  0.0353548   0.02503951
   0.03577073  0.04700108  0.07661592  0.04433907  0.03019715  0.02196157
   0.0108976   0.0074869   0.0291989   0.03951418  0.01372598  0.0176358
   0.02345895  0.0169703   0.02487314  0.01813493  0.0482489   0.01988187
   0.03252641  0.01572249  0.01455786  0.00457533  0.00083188]

Is a list of the probability to be true for every possible label.

EDIT

After reading your comments predict proba is exactly what you want.

Lets make an example. In the following code we have a classifier with 3 classes: either 11, 12 or 13.

If the input is 1 the classifier should predict 11

If the input is 2 the classifier should predict 12

...

If the input is 7 the classifier should predict 13

clf = DecisionTreeClassifier()
clf.fit([[1],[2],[3],[4],[5],[6],[7]], [[11],[12],[13],[13],[12],[11],[13]])

now if you have test data with a single row e.g. 5 than the classifier should predict 12. So lets try that.

clf.predict([[5]])

And voila: the result is array([12])

if we want a probability then predict proba is the way to go:

clf.predict_proba([[5]])

and we get [array([0., 1., 0.])]

In that case the array [0., 1., 0.] means :

0% probability for class 11

100% probability for class 12

0% probability for class 13

If i'm correct thats exactly what you want.
You can even map that to the names of your classes with:

probabilities = clf.predict_proba([[5]])[0]
{clf.classes_[i] : probabilities[i] for i in range(len(probabilities))}

which gives you a dictionary with probabilities for class names:

{11: 0.0, 12: 1.0, 13: 0.0}

Now in your case you have way more classes than only [11,12,13] so the array gets longer. And for every row in your dataset predict_proba creates an array, so for more than a single row of data your output becomes a matrix.


问:
How to improve svm
I apologize in advance for my bad English.

So, I'm working on my final year study project and the description says to make a state of the art on the methods often used to predict churn in telecommunications and then choose two methods that will be applied to the data.

It also says to try to add my contribution to one of the methods.

I chose the decision tree and SVM methods. I would like to add my contribution to the SVM method but I do not know how. I did some research and the most common thing is the "Cross-Validation" method but since it is used by everyone, is it considered a contribution?

I also thought about a hybridization but I'm not sure which algorithm would be best for that.

So I wanted to know if you could give me some ideas to explore in order to try to improve this algorithm, whether in precision, speed or otherwise.

If I sound like a beginner, that's because I am XD.

答:
I am also a beginner in this field , but i can give you some pointers i've come across,

You can look at newer feature generation(Try to do research on that fields specific to telecommunications)

Use different algorithm for imputation(KNN, central imputation).

If you want high accuracy go for XGBOOST .

As this is a churn problem i would concentrate on the recall.

Title: How to improve svm


问:
Django: How to center forms on html template in bootstrap?
I am trying to simply center a form that has been rendered on a Django html template. It is a bootstrap component (form), and I have tried putting the 'center' html tags in various places but with no success. I have tried putting the center tags outside the form, outside the Django templating language blocks, and in the base template, outside the div.

Could someone please advise on a) how to solve the problem b) best practices for applying formatting, as in this case.

Someone tried to edit this suggesting it has nothing to do with Django, but it does. Centering is simple otherwise, but I want to understand it the context of using base templates and django's templating language blocks.

page.html (that extends base2.html)

```<code>{% extends "socialmedia/base2.html" %}
{% load static %}
{% block title %}Welcome to the test page{% endblock %}
{% block heading %}Welcome,,,,{% endblock %}
<center>
{% block content1 %}
<class="form-group row">
    <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group row">
    <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <fieldset class="form-group">
    <div class="row">
      <legend class="col-form-label col-sm-2 pt-0">Radios</legend>
      <div class="col-sm-10">
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
          <label class="form-check-label" for="gridRadios1">
            First radio
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">
          <label class="form-check-label" for="gridRadios2">
            Second radio
          </label>
        </div>
        <div class="form-check disabled">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="option3" disabled>
          <label class="form-check-label" for="gridRadios3">
            Third disabled radio
          </label>
        </div>
      </div>
    </div>
  </fieldset>
  <div class="form-group row">
    <div class="col-sm-2">Checkbox</div>
    <div class="col-sm-10">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" id="gridCheck1">
        <label class="form-check-label" for="gridCheck1">
          Example checkbox
        </label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-10">
      <button type="submit" class="btn btn-primary">Sign in</button>
    </div>
  </div>
</form>

{% endblock %}
</center>
</code>```

base2.html (from which the above file inherits)

```<code><html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="{% static 'worldguestbook\main2.css' %}"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <h1>{% block heading %}My amazing site{% endblock %}</h1>

    <div id="content1">
        {% block content1 %}{% endblock %}
    </div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</body>
</html>
</code>```

答:
try below tag for form It might work</p>

```<code><form ALIGN='center'>
</form>
</code>```

Body:
I am trying to simply center a form that has been rendered on a Django html template. It is a bootstrap component (form), and I have tried putting the 'center' html tags in various places but with no success. I have tried putting the center tags outside the form, outside the Django templating language blocks, and in the base template, outside the div.

Could someone please advise on a) how to solve the problem b) best practices for applying formatting, as in this case.

Someone tried to edit this suggesting it has nothing to do with Django, but it does. Centering is simple otherwise, but I want to understand it the context of using base templates and django's templating language blocks.

page.html (that extends base2.html)

{% extends "socialmedia/base2.html" %}
{% load static %}
{% block title %}Welcome to the test page{% endblock %}
{% block heading %}Welcome,,,,{% endblock %}

{% block content1 %}
<class="form-group row">
    Email

      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

    Password

      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">

  <fieldset class="form-group">

      <legend class="col-form-label col-sm-2 pt-0">Radios</legend>

          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>

            First radio

          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">

            Second radio

          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="option3" disabled>

            Third disabled radio

  </fieldset>

Checkbox

        <input class="form-check-input" type="checkbox" id="gridCheck1">

          Example checkbox

      <button type="submit" class="btn btn-primary">Sign in</button>

</form>

{% endblock %}

base2.html (from which the above file inherits)

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="{% static 'worldguestbook\main2.css' %}"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}My amazing site{% endblock %}</title>

{% block heading %}My amazing site{% endblock %}

        {% block content1 %}{% endblock %}

Body:
try below tag for form It might work

<form ALIGN='center'>
</form>


问:
How can i replicate data with a sql method
I need to copy data. But I uses 2 databases on my application. But when I copy that data I need to insert a new row with the same data. Only I dont know how to do that.

I have already tried somethings so I tried to replicate that data and then the relations but that didnt work for me. So I ask one of my friends and he say you need to use a insert into method.

```<code>public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {

    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $original = Survey::first();

    $new = $original->replicate();
    $new->sid = 123456;
    $new->save();

    foreach($original->groups as $group){

    }

    foreach($original->questions as $question){
        $new->questions()->attach($question);
    }
}
</code>```

my model:

```<code>  public function accuracy() {

    return $this->hasOne( 'App\Models\LimeSurvey\Accuracy', 'survey_id', 'sid' );
}

public function groups() {

    return $this->hasMany( 'App\Models\LimeSurvey\Group', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('group_order', 'asc');
}

public function questions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function parentQuestions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->where('parent_qid', '=', 0)->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function languages() {

    return $this->hasMany( 'App\Models\LimeSurvey\Language', 'surveyls_survey_id', 'sid' );
}
</code>```

答:
You described two types of relations in your model:

1x HasOne (Accuracy)

4x HasMany (groups, questions, parentQuestions and languages)

HasOne relations

You need to copy the related Accuray. That's easy, and you only of to copy the model like you did for the survey.

$original = Survey::first();

// Firstly, clone the survey
$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine

// The clone the accuracy, and attach it to the cloned survey
$originalAccuracy = $original->accuracy;
$newAccuracy = $originalAccuracy->replicate();
$newAccuracy->survey_id = $new->sid;
$newAccuracy->save();
```

<h3>HasMany relations</h3>

<p>You need to copy every related models, one by one. I suggesst doing the following:</p>

<pre class="lang-php prettyprint-override"><code>$original = Survey::first();

$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine

/*
 * Example for groups
 * For each group related with the original survey, we create a clone group, and attach it to the new survey.
 */
$original->groups()->get()->each(function($originalGroup) use ($new) {
    $newGroup = $originalGroup->replicate();
    $newGroup->sid = $new->sid; // Adjust foreign key (in the related table) and local key (in survey table)
    $newGroup->save();
});

</code>```

BelongsToMany relations

Edit: You do not seem to need this part, but I will let it if it can help someone.

As you replicate you model, all your relations should be ok, except the Many-to-Many ones.

I suspect that the problem is linked to your usage of the attach() function. Taken from the Laravel 5.8 documentation (https://laravel.com/docs/5.8/eloquent-relationships#many-to-many):

$user = App\User::find(1);
$user->roles()->attach($roleId);
```

<p>As you can see, the <strong>attach function uses the id</strong> of the role.</p>

<p>Moreover, in your case, you want to attach multiple Many-To-Many models. I would do the following:</p>

<pre class="lang-php prettyprint-override"><code>public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {

    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $original = Survey::first();

    $new = $original->replicate();
    $new->sid = 123456;
    $new->save(); // This is fine

    // Assuming groups() and questions() are BelongsToMany relationships
    $new->groups()->attach($original->groups()->get()->pluck("id")->toArray());
    $new->questions()->attach($original->questions()->get()->pluck("id")->toArray());
}
</code>```

Body:
I need to copy data. But I uses 2 databases on my application. But when I copy that data I need to insert a new row with the same data. Only I dont know how to do that.

I have already tried somethings so I tried to replicate that data and then the relations but that didnt work for me. So I ask one of my friends and he say you need to use a insert into method.

public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {

    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $original = Survey::first();

    $new = $original->replicate();
    $new->sid = 123456;
    $new->save();

    foreach($original->groups as $group){

    }

    foreach($original->questions as $question){
        $new->questions()->attach($question);
    }
}

my model:

  public function accuracy() {

    return $this->hasOne( 'App\Models\LimeSurvey\Accuracy', 'survey_id', 'sid' );
}

public function groups() {

    return $this->hasMany( 'App\Models\LimeSurvey\Group', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('group_order', 'asc');
}

public function questions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function parentQuestions() {

    return $this->hasMany( 'App\Models\LimeSurvey\Question', 'sid', 'sid' )->where('parent_qid', '=', 0)->orderBy('gid', 'asc')->orderBy('question_order', 'asc');
}

public function languages() {

    return $this->hasMany( 'App\Models\LimeSurvey\Language', 'surveyls_survey_id', 'sid' );
}

Body:
You described two types of relations in your model:

1x HasOne (Accuracy)

4x HasMany (groups, questions, parentQuestions and languages)

HasOne relations

You need to copy the related Accuray. That's easy, and you only of to copy the model like you did for the survey.

$original = Survey::first();

// Firstly, clone the survey
$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine

// The clone the accuracy, and attach it to the cloned survey
$originalAccuracy = $original->accuracy;
$newAccuracy = $originalAccuracy->replicate();
$newAccuracy->survey_id = $new->sid;
$newAccuracy->save();

HasMany relations

You need to copy every related models, one by one. I suggesst doing the following:

$original = Survey::first();

$new = $original->replicate();
$new->sid = 123456;
$new->save(); // This is fine

/*
 * Example for groups
 * For each group related with the original survey, we create a clone group, and attach it to the new survey.
 */
$original->groups()->get()->each(function($originalGroup) use ($new) {
    $newGroup = $originalGroup->replicate();
    $newGroup->sid = $new->sid; // Adjust foreign key (in the related table) and local key (in survey table)
    $newGroup->save();
});

BelongsToMany relations

Edit: You do not seem to need this part, but I will let it if it can help someone.

As you replicate you model, all your relations should be ok, except the Many-to-Many ones.

I suspect that the problem is linked to your usage of the attach() function. Taken from the Laravel 5.8 documentation (https://laravel.com/docs/5.8/eloquent-relationships#many-to-many):

$user = App\User::find(1);
$user->roles()->attach($roleId);

As you can see, the attach function uses the id of the role.

Moreover, in your case, you want to attach multiple Many-To-Many models. I would do the following:

public function copySurvey( Manager $fractal, SurveyTransformer $surveyTransformer ) {

    // Copy function (Alleen nog niet volledig hier nog even aanwerken.)
    $original = Survey::first();

    $new = $original->replicate();
    $new->sid = 123456;
    $new->save(); // This is fine

    // Assuming groups() and questions() are BelongsToMany relationships
    $new->groups()->attach($original->groups()->get()->pluck("id")->toArray());
    $new->questions()->attach($original->questions()->get()->pluck("id")->toArray());
}