问:
ASP.NET MVC Identity - Using internal User and Azure AD Authentication together
We are already running an ASP.NET MVC web application which is using internal users via token authentication. This is implemented in the standard way the ASP.NET MVC template provides.

Now we have a requirement to extend this authentication model and allow external Azure AD users to sign into the web application for configured tenant. I have figured out everything on the Azure AD side. Thanks to Microsoft's Azure Samples example.

Now both individual account authentication and Azure AD are working well independently. But they're not working together. When I insert both middleware together its giving issue.

Here's my startup_auth.cs file:

```<code>public partial class Startup
{

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        string ClientId = ConfigurationManager.AppSettings["ida:ClientID"];
        string Authority = "https://login.microsoftonline.com/common/";

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = ClientId,
            Authority = Authority,
            TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuer = false,
            },
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                RedirectToIdentityProvider = (context) =>
                {
                    string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                    context.ProtocolMessage.RedirectUri = appBaseUrl;
                    context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                    return Task.FromResult(0);
                },
                SecurityTokenValidated = (context) =>
                {
                    // retriever caller data from the incoming principal
                    string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                    string UPN = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                    string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                    if (
                        // the caller comes from an admin-consented, recorded issuer
                        (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                        // the caller is recorded in the db of users who went through the individual onboardoing
                        && (db.Users.FirstOrDefault(b =>((b.UPN == UPN) && (b.TenantID == tenantID))) == null)
                        )
                        // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
                        throw new SecurityTokenValidationException();
                    return Task.FromResult(0);
                },
                AuthenticationFailed = (context) =>
                {
                    context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                    context.HandleResponse(); // Suppress the exception
                    return Task.FromResult(0);
                }
            }
        });

    }
}
</code>```

This configuration works well for local user accounts but doesn't work for AAD. To enable AAD authentication, I need to configure the UseCookieAuthentication part as shown below, which will break my local user account authentication.

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions { });
</code>```

Basically I need to remove the local users middleware to get AAD work.

What I mean by AAD not working is, I am not able to go to any secured action which is protected by the [Authorize] attribute. It's calling the SecurityTokenValidated event, and I am able to get all AAD claims and able to validate against my custom tenant. But when I redirect to root of my app (which is a secured action) at the end, it throws me back to my custom login page. Seems it's not internally signing in the user and not creating the necessary authentication cookies.

I would appreciate any ideas on what I could be missing here.

Thanks

答: It sounds like your OpenID Connect auth is not connecting to your Cookie auth.  It looks like you need to specify a SignInAsAuthenticationType in your OpenIdConnectAuthenticationOptions that matches the AuthenticationType in your CookieAuthenticationOptions or your ExternalCookie auth type.

ContentLicense: CC BY-SA 4.0

Body:
We are already running an ASP.NET MVC web application which is using internal users via token authentication. This is implemented in the standard way the ASP.NET MVC template provides.

Now we have a requirement to extend this authentication model and allow external Azure AD users to sign into the web application for configured tenant. I have figured out everything on the Azure AD side. Thanks to Microsoft's Azure Samples example.

Now both individual account authentication and Azure AD are working well independently. But they're not working together. When I insert both middleware together its giving issue.

Here's my startup_auth.cs file:

public partial class Startup
{

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        string ClientId = ConfigurationManager.AppSettings["ida:ClientID"];
        string Authority = "https://login.microsoftonline.com/common/";

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = ClientId,
            Authority = Authority,
            TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuer = false,
            },
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                RedirectToIdentityProvider = (context) =>
                {
                    string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                    context.ProtocolMessage.RedirectUri = appBaseUrl;
                    context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                    return Task.FromResult(0);
                },
                SecurityTokenValidated = (context) =>
                {
                    // retriever caller data from the incoming principal
                    string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                    string UPN = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                    string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                    if (
                        // the caller comes from an admin-consented, recorded issuer
                        (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                        // the caller is recorded in the db of users who went through the individual onboardoing
                        && (db.Users.FirstOrDefault(b =>((b.UPN == UPN) && (b.TenantID == tenantID))) == null)
                        )
                        // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
                        throw new SecurityTokenValidationException();
                    return Task.FromResult(0);
                },
                AuthenticationFailed = (context) =>
                {
                    context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                    context.HandleResponse(); // Suppress the exception
                    return Task.FromResult(0);
                }
            }
        });

    }
}

This configuration works well for local user accounts but doesn't work for AAD. To enable AAD authentication, I need to configure the UseCookieAuthentication part as shown below, which will break my local user account authentication.

app.UseCookieAuthentication(new CookieAuthenticationOptions { });

Basically I need to remove the local users middleware to get AAD work.

What I mean by AAD not working is, I am not able to go to any secured action which is protected by the [Authorize] attribute. It's calling the SecurityTokenValidated event, and I am able to get all AAD claims and able to validate against my custom tenant. But when I redirect to root of my app (which is a secured action) at the end, it throws me back to my custom login page. Seems it's not internally signing in the user and not creating the necessary authentication cookies.

I would appreciate any ideas on what I could be missing here.

Thanks


来源: stackexchange

问:
Can't correctly extract information of a file
I am trying to extract some data of a file. For that purpose have made a script which reads the file and if some keyword is detected, it starts copying and then, when finds a blank line, it stops copying. I think it is not too bad, but is not working.

The python script i wrote is:

```<code>def out_to_mop (namefilein, namefileout):
    print namefilein
    filein=open(namefilein, "r")
    fileout=open(namefileout, "w")
    lines = filein.readlines()
    filein.close()

    #look for keyword "CURRENT.." to start copying
    try:
        indexmaxcycle = lines.index("          CURRENT BEST VALUE OF HEAT OF FORMATION")
        indexmaxcycle += 5
    except:
        indexmaxcycle = 0

    if indexmaxcycle != 0:
        while lines[indexmaxcycle]!=" \n":
            linediv = lines[indexmaxcycle].split()
            symbol = linediv[0]
            x = float(linediv[1])
            indexmaxcycle += 1
            fileout.write("%s \t %3.8f 1 \n" %(symbol, x))
    else:
        print "structure not found"
        exit()
    fileout.close()
</code>```

This function is supposed to extract info from this file called file1.out:

```<code>          CURRENT BEST VALUE OF HEAT OF FORMATION =  -1161.249249
  cycles=200 pm6 opt singlet eps=80   charge=-1

  C    -3.87724655 +1   1.30585983 +1   4.53273224 +1
  H    -7.60628859 +1   0.53968618 +1   3.72680573 +1
  O    -4.76978297 +1   4.45409715 +1   1.42608903 +1
  H    -4.66890488 +1   4.47267425 +1   2.41952335 +1
  H    -5.59468165 +1   3.93399792 +1   1.27757138 +1

 **********************
 *                    *
 * JOB ENDED NORMALLY *
 *                    *
 **********************
</code>```

but it prints "structure not found"

Would you help me a bit?

答:
You try to find the beginning of the structure with the code line

```<code>indexmaxcycle = lines.index("          CURRENT BEST VALUE OF HEAT OF FORMATION")
</code>```

The documentation for the index method says, "Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item." However, that line you are searching for is not one of the file lines. The actual file line is

```<code>          CURRENT BEST VALUE OF HEAT OF FORMATION =  -1161.249249
</code>```

Note the number at the end, which is not in your search string. Therefore, the index method raises an exception and you get an indexmaxcycle value of zero.

Since you apparently do not know the full contents of the file line in advance, you should loop through the input lines yourself and use the in operator to find a line that contains your search string. You could also use the startswith string method in this way:

```<code>for j, line in enumerate(lines):
    if line.startswith("          CURRENT BEST VALUE OF HEAT OF FORMATION"):
        indexmaxcycle = j + 5
        break
else:
    indexmaxcycle = 0
</code>```

I dropped the try..except structure here, since I see no way an exception could be raised for this code. I could be wrong, of course.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to extract some data of a file. For that purpose have made a script which reads the file and if some keyword is detected, it starts copying and then, when finds a blank line, it stops copying. I think it is not too bad, but is not working.

The python script i wrote is:

def out_to_mop (namefilein, namefileout):
    print namefilein
    filein=open(namefilein, "r")
    fileout=open(namefileout, "w")
    lines = filein.readlines()
    filein.close()

    #look for keyword "CURRENT.." to start copying
    try:
        indexmaxcycle = lines.index("          CURRENT BEST VALUE OF HEAT OF FORMATION")
        indexmaxcycle += 5
    except:
        indexmaxcycle = 0

    if indexmaxcycle != 0:
        while lines[indexmaxcycle]!=" \n":
            linediv = lines[indexmaxcycle].split()
            symbol = linediv[0]
            x = float(linediv[1])
            indexmaxcycle += 1
            fileout.write("%s \t %3.8f 1 \n" %(symbol, x))
    else:
        print "structure not found"
        exit()
    fileout.close()

This function is supposed to extract info from this file called file1.out:

          CURRENT BEST VALUE OF HEAT OF FORMATION =  -1161.249249
  cycles=200 pm6 opt singlet eps=80   charge=-1

  C    -3.87724655 +1   1.30585983 +1   4.53273224 +1
  H    -7.60628859 +1   0.53968618 +1   3.72680573 +1
  O    -4.76978297 +1   4.45409715 +1   1.42608903 +1
  H    -4.66890488 +1   4.47267425 +1   2.41952335 +1
  H    -5.59468165 +1   3.93399792 +1   1.27757138 +1

 **********************
 *                    *
 * JOB ENDED NORMALLY *
 *                    *
 **********************

but it prints "structure not found"

Would you help me a bit?

Body:
You try to find the beginning of the structure with the code line

indexmaxcycle = lines.index("          CURRENT BEST VALUE OF HEAT OF FORMATION")

The documentation for the index method says, "Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item." However, that line you are searching for is not one of the file lines. The actual file line is

          CURRENT BEST VALUE OF HEAT OF FORMATION =  -1161.249249

Note the number at the end, which is not in your search string. Therefore, the index method raises an exception and you get an indexmaxcycle value of zero.

Since you apparently do not know the full contents of the file line in advance, you should loop through the input lines yourself and use the in operator to find a line that contains your search string. You could also use the startswith string method in this way:

for j, line in enumerate(lines):
    if line.startswith("          CURRENT BEST VALUE OF HEAT OF FORMATION"):
        indexmaxcycle = j + 5
        break
else:
    indexmaxcycle = 0

I dropped the try..except structure here, since I see no way an exception could be raised for this code. I could be wrong, of course.


问:
Comparator isn't being called
```<code>List<UserContribution> userContributions = new ArrayList<>();
...
Collections.sort(userContributions, new Comparator<UserContribution>() {
    @Override
    public int compare(UserContribution o1, UserContribution o2) {
        return o1.date.after(o2.date) ? -1 : o1.date.before(o2.date) ? 1 : 0;
    }
});
</code>```

userContributions ends up with 3 items in it.  A breakpoint set in the compare method is not getting hit (and Android Studio is showing it as not a valid breakpoint) and thus my items aren't getting sorted.  Why come?

Thanks!

答:
I would suggest avoiding the nested ternary operation, or delegating the compare method to the class being compared. This makes the code more readable, helps avoid potential ordering errors in the comparison, and will allow you to insert breakpoints in each branch to see the result of the comparison.

Option 1: Full conditional structure

```<code>public int compare(UserContributions o1, UserContributions o2) {
    if (o1.date.after(o2)) {
        return 1;
    else if (o1.date.before(o2)) {
        return -1;
    else {
        return 0;
    }
}
</code>```

Note this is an error prone method because you are reliant on date.before() and date.after() correctly mimicking the operations < and >. I personally prefer Option 2.

Option 2: Delegate comparison to dates

```<code>public int compare(UserContributions o1, UserContributions o2) {
    return o1.date.compareTo(o2.date);
}
</code>```

Note the date.compare() method would take care of defining a comparison of dates.

Title: Comparator isn't being called

Body:
List<UserContribution> userContributions = new ArrayList<>();
...
Collections.sort(userContributions, new Comparator<UserContribution>() {
    @Override
    public int compare(UserContribution o1, UserContribution o2) {
        return o1.date.after(o2.date) ? -1 : o1.date.before(o2.date) ? 1 : 0;
    }
});

userContributions ends up with 3 items in it.  A breakpoint set in the compare method is not getting hit (and Android Studio is showing it as not a valid breakpoint) and thus my items aren't getting sorted.  Why come?

Thanks!

Body:
I would suggest avoiding the nested ternary operation, or delegating the compare method to the class being compared. This makes the code more readable, helps avoid potential ordering errors in the comparison, and will allow you to insert breakpoints in each branch to see the result of the comparison.

Option 1: Full conditional structure

public int compare(UserContributions o1, UserContributions o2) {
    if (o1.date.after(o2)) {
        return 1;
    else if (o1.date.before(o2)) {
        return -1;
    else {
        return 0;
    }
}

Note this is an error prone method because you are reliant on date.before() and date.after() correctly mimicking the operations < and >. I personally prefer Option 2.

Option 2: Delegate comparison to dates

public int compare(UserContributions o1, UserContributions o2) {
    return o1.date.compareTo(o2.date);
}

Note the date.compare() method would take care of defining a comparison of dates.


问:
STM32F407 and ARDUINO UART Communication
I have been trying to communicate the STM32F407 Discovery and Arduino Mega with UART.I have a MAX232 module.STM32F4's PD8 and PD9 pins are connected to the MAX232 Module.Output of the modul is connected to the Arduino's Rx-Tx pins.All connections are double-checked.
And I transmitted a character "A" from STM to Arduino.In ASCII table,decimal value of the A is 65 in ASCII table.However,the Arduino's Serial Port read 95 in decimal.

I need a solution or idea about that Wrong Received/Transmitted values ?

Thanks,

```<code>/*  STM32F4 CODE */
#include "stm32f4xx_hal.h"
#include <stdio.h>

ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;

UART_HandleTypeDef huart3;

void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_ADC3_Init(void);

int main(void)
{
  HAL_Init();

  SystemClock_Config();

  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_ADC3_Init();

  __HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);

  char *buffer[10] = "00000000";

  while (1)
  {
        HAL_UART_Transmit_IT(&huart3,(uint8_t *)buffer,8);
        HAL_Delay(1000);
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                          |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
  Error_Handler();
  }
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_10B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
   }
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_144CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC2 init function */
static void MX_ADC2_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc2.Init.Resolution = ADC_RESOLUTION_8B;
  hadc2.Init.ScanConvMode = DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
   {
  Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_11;
  sConfig.Rank = 1;
 sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC3 init function */
static void MX_ADC3_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc3.Init.Resolution = ADC_RESOLUTION_12B;
  hadc3.Init.ScanConvMode = DISABLE;
  hadc3.Init.ContinuousConvMode = DISABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 1;
  hadc3.Init.DMAContinuousRequests = DISABLE;
  hadc3.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_12;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* USART3 init function */
static void MX_USART3_UART_Init(void)
{
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 9600;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
}
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOE, Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(POWER_LED_GPIO_Port, POWER_LED_Pin, GPIO_PIN_SET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOD, IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, Relay_Pin|BUZZER_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pins : Q1_Pin Q2_Pin Q3_Pin Q4_Pin
                           A_Pin B_Pin C_Pin D_Pin
                           E_Pin F_Pin G_Pin DP_Pin */
  GPIO_InitStruct.Pin = Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
  /*Configure GPIO pin : POWER_LED_Pin */
  GPIO_InitStruct.Pin = POWER_LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(POWER_LED_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : B3_Pin B4_Pin */
  GPIO_InitStruct.Pin = B3_Pin|B4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
  /*Configure GPIO pin : B0_Pin */
  GPIO_InitStruct.Pin = B0_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(B0_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : IN1_Pin IN2_Pin IN3_Pin IN4_Pin */
  GPIO_InitStruct.Pin = IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
  /*Configure GPIO pins : B1_Pin B2_Pin */
  GPIO_InitStruct.Pin = B1_Pin|B2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  /*Configure GPIO pin : Digital_Temp_Pin */
  GPIO_InitStruct.Pin = Digital_Temp_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Digital_Temp_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : Relay_Pin BUZZER_Pin */
  GPIO_InitStruct.Pin = Relay_Pin|BUZZER_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void Error_Handler(void)
{
  while(1)
  {
  }
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
}
#endif
</code>```

$

答:
First of all, you said that "I transmitted a character "A" from STM to Arduino", however i haven't seen anything about that.

You should not define buffer as a char pointer. Define buffer as char or uint8_t array or variable and call HAL_UART_Transmit_IT method with pointer of buffer as following.

```<code>uint8_t buffer = 0x41;   // hex value of A is 0x41

while (1)
{
      HAL_UART_Transmit_IT(&huart3,&buffer,8);
      HAL_Delay(1000);
}
</code>```

Also, most important thing is that baudrates of STM board and Arduino should be the same. If baudrates are different from each other, you will read wrong value.

Body:
I have been trying to communicate the STM32F407 Discovery and Arduino Mega with UART.I have a MAX232 module.STM32F4's PD8 and PD9 pins are connected to the MAX232 Module.Output of the modul is connected to the Arduino's Rx-Tx pins.All connections are double-checked.
And I transmitted a character "A" from STM to Arduino.In ASCII table,decimal value of the A is 65 in ASCII table.However,the Arduino's Serial Port read 95 in decimal.

I need a solution or idea about that Wrong Received/Transmitted values ?

Thanks,

/*  STM32F4 CODE */
#include "stm32f4xx_hal.h"
#include <stdio.h>

ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;

UART_HandleTypeDef huart3;

void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_ADC3_Init(void);

int main(void)
{
  HAL_Init();

  SystemClock_Config();

  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_ADC3_Init();

  __HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);

  char *buffer[10] = "00000000";

  while (1)
  {
        HAL_UART_Transmit_IT(&huart3,(uint8_t *)buffer,8);
        HAL_Delay(1000);
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                          |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
  Error_Handler();
  }
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_10B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
   }
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_144CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC2 init function */
static void MX_ADC2_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc2.Init.Resolution = ADC_RESOLUTION_8B;
  hadc2.Init.ScanConvMode = DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
   {
  Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_11;
  sConfig.Rank = 1;
 sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC3 init function */
static void MX_ADC3_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc3.Init.Resolution = ADC_RESOLUTION_12B;
  hadc3.Init.ScanConvMode = DISABLE;
  hadc3.Init.ContinuousConvMode = DISABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 1;
  hadc3.Init.DMAContinuousRequests = DISABLE;
  hadc3.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_12;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* USART3 init function */
static void MX_USART3_UART_Init(void)
{
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 9600;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
}
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOE, Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(POWER_LED_GPIO_Port, POWER_LED_Pin, GPIO_PIN_SET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOD, IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, Relay_Pin|BUZZER_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pins : Q1_Pin Q2_Pin Q3_Pin Q4_Pin
                           A_Pin B_Pin C_Pin D_Pin
                           E_Pin F_Pin G_Pin DP_Pin */
  GPIO_InitStruct.Pin = Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
  /*Configure GPIO pin : POWER_LED_Pin */
  GPIO_InitStruct.Pin = POWER_LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(POWER_LED_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : B3_Pin B4_Pin */
  GPIO_InitStruct.Pin = B3_Pin|B4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
  /*Configure GPIO pin : B0_Pin */
  GPIO_InitStruct.Pin = B0_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(B0_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : IN1_Pin IN2_Pin IN3_Pin IN4_Pin */
  GPIO_InitStruct.Pin = IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
  /*Configure GPIO pins : B1_Pin B2_Pin */
  GPIO_InitStruct.Pin = B1_Pin|B2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  /*Configure GPIO pin : Digital_Temp_Pin */
  GPIO_InitStruct.Pin = Digital_Temp_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Digital_Temp_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : Relay_Pin BUZZER_Pin */
  GPIO_InitStruct.Pin = Relay_Pin|BUZZER_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void Error_Handler(void)
{
  while(1)
  {
  }
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
}
#endif

$

Body:
First of all, you said that "I transmitted a character "A" from STM to Arduino", however i haven't seen anything about that.

You should not define buffer as a char pointer. Define buffer as char or uint8_t array or variable and call HAL_UART_Transmit_IT method with pointer of buffer as following.

uint8_t buffer = 0x41;   // hex value of A is 0x41

while (1)
{
      HAL_UART_Transmit_IT(&huart3,&buffer,8);
      HAL_Delay(1000);
}

Also, most important thing is that baudrates of STM board and Arduino should be the same. If baudrates are different from each other, you will read wrong value.


问:
More efficient way to multiply each column of a 2-d matrix by each slice of a 3-d matrix
I have an 8x8x25000 array W and an 8 x 25000 array r. I want to multiple each 8x8 slice of W by each column (8x1) of r and save the result in Wres, which will end up being an 8x25000 matrix.

I am accomplishing this using a for loop as such:

```<code>for i in range(0,25000):
    Wres[:,i] = np.matmul(W[:,:,i],res[:,i])
</code>```

But this is slow and I am hoping there is a quicker way to accomplish this.

Any ideas?

答:
Matmul can propagate as long as the 2 arrays share the same 1 axis length. From the docs:

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

Thus, you have to perform 2 operations prior to matmul:

```<code>import numpy as np
a = np.random.rand(8,8,100)
b = np.random.rand(8, 100)
</code>```

transpose a and b so that the first axis are the 100 slices

add an extra dimension to b so that b.shape = (100, 8, 1)

Then:

```<code> at = a.transpose(2, 0, 1) # swap to shape 100, 8, 8
 bt = b.T[..., None] # swap to shape 100, 8, 1
 c = np.matmul(at, bt)
</code>```

c is now 100, 8, 1, reshape back to 8, 100:

```<code> c = np.squeeze(c).swapaxes(0, 1)
</code>```

or

```<code> c = np.squeeze(c).T
</code>```

And last, a one-liner just for conveniende:

```<code>c = np.squeeze(np.matmul(a.transpose(2, 0, 1), b.T[..., None])).T
</code>```

Body:
I have an 8x8x25000 array W and an 8 x 25000 array r. I want to multiple each 8x8 slice of W by each column (8x1) of r and save the result in Wres, which will end up being an 8x25000 matrix.

I am accomplishing this using a for loop as such:

for i in range(0,25000):
    Wres[:,i] = np.matmul(W[:,:,i],res[:,i])

But this is slow and I am hoping there is a quicker way to accomplish this.

Any ideas?

Body:
Matmul can propagate as long as the 2 arrays share the same 1 axis length. From the docs:

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

Thus, you have to perform 2 operations prior to matmul:

import numpy as np
a = np.random.rand(8,8,100)
b = np.random.rand(8, 100)

transpose a and b so that the first axis are the 100 slices

add an extra dimension to b so that b.shape = (100, 8, 1)

Then:

 at = a.transpose(2, 0, 1) # swap to shape 100, 8, 8
 bt = b.T[..., None] # swap to shape 100, 8, 1
 c = np.matmul(at, bt)

c is now 100, 8, 1, reshape back to 8, 100:

 c = np.squeeze(c).swapaxes(0, 1)

or

 c = np.squeeze(c).T

And last, a one-liner just for conveniende:

c = np.squeeze(np.matmul(a.transpose(2, 0, 1), b.T[..., None])).T


问:
PHPUnit - Mark test as failed when two related functions fail
I started using PHPUnit for unit testing recently and I structured my tests to check correct behavior when a function succeeds and fails.

For example I could test function connectToDevice() expecting that when connection succeeds it returns true, otherwise it returns false. Then I would have:

```<code>public function testConnectToDeviceSuccess()
{
    $this->assertTrue($this->myObject->connectToDevice());
}

public function testConnectToDeviceFailure()
{
    $this->assertFalse($this->myObject->connectToDevice());
}
</code>```

At the moment one of those function will necessarily fail, then PHPUnit will report me 1 fail. Instead I would set it to mark test failed only when both functions fail. Therefore when 1 succeeds the other will be skipped.

Is this possible in PHPUnit maintaining those tests in two different functions?

答:
It is possible (you can make one test depend on the outcome of another test, see Test Dependencies), however consider what you would test effectively in your questions here, wrapping that in one test:

```<code>public function testConnectToDeviceBehavior()
{
    $actual = $this->myObject->connectToDevice() === $this->myObject->connectToDevice();
    $this->assertTrue($actual);
}
</code>```

This will make the test fail if, and only if, connecting to the device does not twice give the same result.

You could write that with test dependencies over multiple tests, however this is most likely not what you want to test in the end.

However if, check the linked section of the Phpunit docs.

Otherwise consider what is outlined in the other answer, using dependency injection and test your object with a working and a failing connect to the device.

Body:
I started using PHPUnit for unit testing recently and I structured my tests to check correct behavior when a function succeeds and fails.

For example I could test function connectToDevice() expecting that when connection succeeds it returns true, otherwise it returns false. Then I would have:

public function testConnectToDeviceSuccess()
{
    $this->assertTrue($this->myObject->connectToDevice());
}

public function testConnectToDeviceFailure()
{
    $this->assertFalse($this->myObject->connectToDevice());
}

At the moment one of those function will necessarily fail, then PHPUnit will report me 1 fail. Instead I would set it to mark test failed only when both functions fail. Therefore when 1 succeeds the other will be skipped.

Is this possible in PHPUnit maintaining those tests in two different functions?

Body:
It is possible (you can make one test depend on the outcome of another test, see Test Dependencies), however consider what you would test effectively in your questions here, wrapping that in one test:

public function testConnectToDeviceBehavior()
{
    $actual = $this->myObject->connectToDevice() === $this->myObject->connectToDevice();
    $this->assertTrue($actual);
}

This will make the test fail if, and only if, connecting to the device does not twice give the same result.

You could write that with test dependencies over multiple tests, however this is most likely not what you want to test in the end.

However if, check the linked section of the Phpunit docs.

Otherwise consider what is outlined in the other answer, using dependency injection and test your object with a working and a failing connect to the device.


问:
When using Git how to make sure all people can use referenced dll
I'm a Git beginner.
When using visual studio 2017 c# and Git.
How should one make a reference to a required dll, for a solution.
So that other people joining the git, but put their repro a different local computer folder, still can use the same dll's. Apperantly visual studio uses local path's, and i dont know how to make them relative.

Because if people would each alter the reference path i get lots of updates on that dll link, but every time someone corrects it for his computer then all others need to adjust it again.

答:
The reference paths are relative so it will not be an issue.

One normally uses https://www.nuget.org/ for package management of 3rd party dlls. However, you can still add your own dlls and reference them by relative path.

For example, my csproj file:

```<code><Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
  <HintPath>..\packages\log4net.2.0.5\lib\net45-full\log4net.dll</HintPath>
  <Private>True</Private>
</Reference>
</code>```

In this example, packages is a folder in the root of the git repository and the .csproj is also in a folder in the root.

Body:
The reference paths are relative so it will not be an issue.

One normally uses https://www.nuget.org/ for package management of 3rd party dlls. However, you can still add your own dlls and reference them by relative path.

For example, my csproj file:

<Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
  <HintPath>..\packages\log4net.2.0.5\lib\net45-full\log4net.dll</HintPath>
  <Private>True</Private>
</Reference>

In this example, packages is a folder in the root of the git repository and the .csproj is also in a folder in the root.


问:
Efficient container for different derived classes in C++
When programming games, I used to store all game Objects in a std::vector with initialized and fixed size. Recently I felt the need for some inheritance among the game object classes.

So lets assume I have like 40 classes derived from my class Enemy. If I want to store objects/instances of those classes in a vector, I only have the option of storing them as vector Enemy* right? So the only thing thats contiguously allocated are the pointers, right? So I still will have a lot of cache misses when those need to be dereferenced, right?

Is there any "best practice" way, of storing derived classes in coniguous allocated memory, so that looping through them takes the minimum amount of time?

答:
Boost just accepted a library for exactly this purpose: poly_collection. In particular, you are looking for base_collection

Internally, it uses a number of vectors, one per (derived) type, while providing an interface close to standard containers.

This article by its author provides some design background and a comparison to other solutions, like a vector of unique_ptr. The advantage is two-fold: first, by not using pointers and dynamic memory allocation per element you have better memory locality, and second, grouping elements of the same type together, you help branch prediction and instruction cache for virtual member functions.


问:
Can't get attribute 'abc' on <module '__main__' from 'abc_h.py'>
I am defining a function in  python. Program file name itself is abc_d.py . I don't understand if i can import the same file inside again.

```<code>import numpy as np
import matplotlib.pyplot as plt
import sys
import multiprocessing
num_processor=4
pool = multiprocessing.Pool(num_processor)

def abc(data):
    w=np.dot(data.reshape(25,1),data.reshape(1,25))
    return w

data_final=np.array(range(100))
n=100
error=[]
k_list=[50,100,500,1000,2000]
for k in k_list:

    dict_data={}
    for d_set in range(num_processor):
        dict_data[d_set]=data_final[int(d_set*n/4):int((d_set+1)*n/4)]
        if(d_set==num_processor-1):
            dict_data[d_set]=data_final[int(d_set*n/4):]

    tasks = dict_data
    results_w=[pool.apply_async(abc,dict_data[t]) for t in range(num_processor)]
    w_f=[]
    for result in results_w:
        w_s=result.get()
        w_f.append(w_s.tolist())

    w_f=np.array(w_f)

print (w_f)
</code>```

where tasks is a dictionary with array.

Error:

Can anybody explain the error. I am still not much familiar with the python.

```<code>Process ForkPoolWorker-1:
Process ForkPoolWorker-2:
Process ForkPoolWorker-3:
Process ForkPoolWorker-4:
Traceback (most recent call last):
Traceback (most recent call last):
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 254, in _bootstrap
    self.run()
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/home/anaconda3/lib/python3.5/multiprocessing/pool.py", line 108, in worker
    task = get()
  File "/home/anaconda3/lib/python3.5/multiprocessing/queues.py", line 345, in get
    return ForkingPickler.loads(res)
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 254, in _bootstrap
    self.run()
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
AttributeError: Can't get attribute 'abc' on <module '__main__' from 'abc_d.py'>
</code>```

答:
If you declare the pool prior to declaring the function you are trying to use in parallel it will throw this error. Reverse the order and it will no longer throw this error. Also, there is a bug in your code, you are feeding all of your data_dict to abc, when you want to feed it as a list. So I changed that line too and it returns some results.</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import sys
import multiprocessing
num_processor=4

def abc(data):
    w=np.dot(data.reshape(25,1),data.reshape(1,25))
    return w

pool = multiprocessing.Pool(num_processor)

data_final=np.array(range(100))
n=100
error=[]
k_list=[50,100,500,1000,2000]
for k in k_list:

    dict_data={}
    for d_set in range(num_processor):
        dict_data[d_set]=data_final[int(d_set*n/4):int((d_set+1)*n/4)]
        if(d_set==num_processor-1):
            dict_data[d_set]=data_final[int(d_set*n/4):]

    tasks = dict_data
    results_w=[pool.apply_async(abc, [dict_data[t]]) for t in range(num_processor)]
    w_f=[]
    for result in results_w:
        w_s=result.get()
        w_f.append(w_s.tolist())

    w_f=np.array(w_f)

print (w_f)
</code>```

Body:
I am defining a function in  python. Program file name itself is abc_d.py . I don't understand if i can import the same file inside again.

import numpy as np
import matplotlib.pyplot as plt
import sys
import multiprocessing
num_processor=4
pool = multiprocessing.Pool(num_processor)

def abc(data):
    w=np.dot(data.reshape(25,1),data.reshape(1,25))
    return w

data_final=np.array(range(100))
n=100
error=[]
k_list=[50,100,500,1000,2000]
for k in k_list:

    dict_data={}
    for d_set in range(num_processor):
        dict_data[d_set]=data_final[int(d_set*n/4):int((d_set+1)*n/4)]
        if(d_set==num_processor-1):
            dict_data[d_set]=data_final[int(d_set*n/4):]

    tasks = dict_data
    results_w=[pool.apply_async(abc,dict_data[t]) for t in range(num_processor)]
    w_f=[]
    for result in results_w:
        w_s=result.get()
        w_f.append(w_s.tolist())

    w_f=np.array(w_f)

print (w_f)

where tasks is a dictionary with array.

Error:

Can anybody explain the error. I am still not much familiar with the python.

Process ForkPoolWorker-1:
Process ForkPoolWorker-2:
Process ForkPoolWorker-3:
Process ForkPoolWorker-4:
Traceback (most recent call last):
Traceback (most recent call last):
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 254, in _bootstrap
    self.run()
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/home/anaconda3/lib/python3.5/multiprocessing/pool.py", line 108, in worker
    task = get()
  File "/home/anaconda3/lib/python3.5/multiprocessing/queues.py", line 345, in get
    return ForkingPickler.loads(res)
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 254, in _bootstrap
    self.run()
  File "/home/anaconda3/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
AttributeError: Can't get attribute 'abc' on <module '__main__' from 'abc_d.py'>

Body:
If you declare the pool prior to declaring the function you are trying to use in parallel it will throw this error. Reverse the order and it will no longer throw this error. Also, there is a bug in your code, you are feeding all of your data_dict to abc, when you want to feed it as a list. So I changed that line too and it returns some results.

import numpy as np
import matplotlib.pyplot as plt
import sys
import multiprocessing
num_processor=4

def abc(data):
    w=np.dot(data.reshape(25,1),data.reshape(1,25))
    return w

pool = multiprocessing.Pool(num_processor)

data_final=np.array(range(100))
n=100
error=[]
k_list=[50,100,500,1000,2000]
for k in k_list:

    dict_data={}
    for d_set in range(num_processor):
        dict_data[d_set]=data_final[int(d_set*n/4):int((d_set+1)*n/4)]
        if(d_set==num_processor-1):
            dict_data[d_set]=data_final[int(d_set*n/4):]

    tasks = dict_data
    results_w=[pool.apply_async(abc, [dict_data[t]]) for t in range(num_processor)]
    w_f=[]
    for result in results_w:
        w_s=result.get()
        w_f.append(w_s.tolist())

    w_f=np.array(w_f)

print (w_f)


问:
gulp plugin - to merge broken js files into one js file?
I have read all the answers on the internet that I could find on this subject in last two days. Now I am just searching for gulp plugin that can merge broken js files into one big js file and not to throw error in terminal caused by unclosed function in one js file.

Explanation:

I have created js app built with modules.
At the very beginning I didn't knew that this will become big app and therefore I have wrote js code in one file.

Now I have come to an idea to split app.js file like this:

app-start.js (Named IIFE function open)

module1.js

module2.js

etc.

app-end.js  (Named IIFE function closed)

I am using gulp as task runner and gulp-concat which works perfectly.

Problem is that when I try to break IIFE function in two files (app-start.js, app-end.js) then gulp doesn't wanna build bundle.js file.
I get error in terminal that I should repair my js code in

app-start.js

So, my question is,

do You maybe know about gulp plugin that will merge multiple js files in given order and never mind the js code errors in those files?

This is my gulp.js code:

```<code>    var gulp = require('gulp'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    plumber = require('gulp-plumber'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create(),
    sourceMap = require('gulp-sourcemaps'),
    babel = require('gulp-babel');

    gulp.task('sass', function() {
    gulp.src('resources/sass/config-normalize.sass')
    //.pipe(sourceMap.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer({browsers: ['last 30 versions']}))
    .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
    //.pipe(sourceMap.write('.'))
    .pipe(gulp.dest('configurator/css'));

    gulp.src('resources/sass/config-style.sass')
    //.pipe(sourceMap.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer({browsers: ['last 30 versions']}))
    .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
    //.pipe(sourceMap.write('.'))
    .pipe(gulp.dest('configurator/css'))
    .pipe(browserSync.stream());
});

gulp.task('scripts', function() {
    gulp.src([
        //'resources/js/vendor/jquery.js',
        //'resources/js/vendor/library/neki_file.js',
        'resources/js/001-app-start.js',
        'resources/js/002-ajax.js',
        'resources/js/003-global-variables.js',

        'resources/js/050-main.js',

        'resources/js/100-my-modules.js',
        'resources/js/app-end.js'
        ])
    //.pipe(plumber())
    .pipe(babel({
            presets: ['es2015']
        }))
    .pipe(concat('all.js'))
    //.pipe(uglify())
    .pipe(gulp.dest('configurator/js'))
    .pipe(browserSync.stream());
});

gulp.task('php', function() {
    gulp.src('./**/*.php')
    .pipe(browserSync.stream());
});

gulp.task('browser-sync', function() {
    browserSync.init({
        proxy: "localhost"     //Upisi path do projekta na local hostu bez http://
    });
});

gulp.task('images', function() {
    return gulp.src('assets/images-uncompressed/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('build/images'));
});

gulp.task('watch', function() {
    gulp.watch('./**/*.php', ['php']);
    gulp.watch('resources/sass/**', ['sass']);
    gulp.watch('resources/js/**', ['scripts']);
    //gulp.watch('resources/images-uncompressed/*', ['images']);
});

gulp.task('default', ['sass', 'scripts', 'php', 'browser-sync', 'watch']);
</code>```

答:
The problem is with the order you run your Gulp tasks:

babel parses and transforms JavaScript so it needs well-formed input.

concat doesn't need to understand JavaScript; it just combines text files. It will happily deal with your broken-up files.

If you move concat before babel, Babel can work on a single, well-formed blob of JavaScript built up from your split files.

Body:
I have read all the answers on the internet that I could find on this subject in last two days. Now I am just searching for gulp plugin that can merge broken js files into one big js file and not to throw error in terminal caused by unclosed function in one js file.

Explanation:

I have created js app built with modules.
At the very beginning I didn't knew that this will become big app and therefore I have wrote js code in one file.

Now I have come to an idea to split app.js file like this:

app-start.js (Named IIFE function open)

module1.js

module2.js

etc.

app-end.js  (Named IIFE function closed)

I am using gulp as task runner and gulp-concat which works perfectly.

Problem is that when I try to break IIFE function in two files (app-start.js, app-end.js) then gulp doesn't wanna build bundle.js file.
I get error in terminal that I should repair my js code in

app-start.js

So, my question is,

do You maybe know about gulp plugin that will merge multiple js files in given order and never mind the js code errors in those files?

This is my gulp.js code:

    var gulp = require('gulp'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    plumber = require('gulp-plumber'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create(),
    sourceMap = require('gulp-sourcemaps'),
    babel = require('gulp-babel');

    gulp.task('sass', function() {
    gulp.src('resources/sass/config-normalize.sass')
    //.pipe(sourceMap.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer({browsers: ['last 30 versions']}))
    .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
    //.pipe(sourceMap.write('.'))
    .pipe(gulp.dest('configurator/css'));

    gulp.src('resources/sass/config-style.sass')
    //.pipe(sourceMap.init())
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(autoprefixer({browsers: ['last 30 versions']}))
    .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed
    //.pipe(sourceMap.write('.'))
    .pipe(gulp.dest('configurator/css'))
    .pipe(browserSync.stream());
});

gulp.task('scripts', function() {
    gulp.src([
        //'resources/js/vendor/jquery.js',
        //'resources/js/vendor/library/neki_file.js',
        'resources/js/001-app-start.js',
        'resources/js/002-ajax.js',
        'resources/js/003-global-variables.js',

        'resources/js/050-main.js',

        'resources/js/100-my-modules.js',
        'resources/js/app-end.js'
        ])
    //.pipe(plumber())
    .pipe(babel({
            presets: ['es2015']
        }))
    .pipe(concat('all.js'))
    //.pipe(uglify())
    .pipe(gulp.dest('configurator/js'))
    .pipe(browserSync.stream());
});

gulp.task('php', function() {
    gulp.src('./**/*.php')
    .pipe(browserSync.stream());
});

gulp.task('browser-sync', function() {
    browserSync.init({
        proxy: "localhost"     //Upisi path do projekta na local hostu bez http://
    });
});

gulp.task('images', function() {
    return gulp.src('assets/images-uncompressed/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('build/images'));
});

gulp.task('watch', function() {
    gulp.watch('./**/*.php', ['php']);
    gulp.watch('resources/sass/**', ['sass']);
    gulp.watch('resources/js/**', ['scripts']);
    //gulp.watch('resources/images-uncompressed/*', ['images']);
});

gulp.task('default', ['sass', 'scripts', 'php', 'browser-sync', 'watch']);


问:
Debian Stretch upgrade: Deinstalled docker cloud, still in apt lists
I've tried to install docker cloud several months ago but I removed it. Now I have updated to Debian Stretch from Jessie and I get this error when I update via "apt-get update" and don't know how to solve it. Can anyone offer some help? Thanks!</p>

```<code>sudo apt-get update
Get:1 http://debian.mirrors.ovh.net/debian stretch-updates InRelease
Ign:2 http://debian.mirrors.ovh.net/debian stretch InRelease
Get:3 http://repo.cloud.docker.com/ubuntu dockercloud InRelease [1,383 B]
Get:4 http://debian.mirrors.ovh.net/debian stretch Release
Hit:5 https://deb.nodesource.com/node_6.x jessie InRelease
Hit:6 https://apt.dockerproject.org/repo debian-stretch InRelease
Hit:7 http://security.debian.org stretch/updates InRelease
Ign:8 http://download.draios.com/stable/deb stable-amd64/ InRelease
Hit:9 http://download.draios.com/stable/deb stable-amd64/ Release
Ign:3 http://repo.cloud.docker.com/ubuntu dockercloud InRelease
Fetched 203 kB in 0s (247 kB/s)
Reading package lists... Done
W: GPG error: http://repo.cloud.docker.com/ubuntu dockercloud InRelease: The following signatures were invalid: 278FE7333CFF7F8B60B677E85DD27147EF170D1C
W: The repository 'http://repo.cloud.docker.com/ubuntu dockercloud InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
</code>```

答:
```<code>W: GPG error: http://repo.cloud.docker.com/ubuntu dockercloud InRelease: The following signatures were invalid: 278FE7333CFF7F8B60B677E85DD27147EF170D1C
W: The repository 'http://repo.cloud.docker.com/ubuntu dockercloud InRelease' is not signed.
</code>```

Actually this is a Warning not an Error.
It seems that somewhere in Your SourcesList(e.g. /etc/apt/sources.list) You still have a docker repo.

```<code>$ sudo grep -w "docker.com" /etc/apt/*.*
</code>```

will show where is docker's url. If You do not need it any more, just comment this line.

Well, if You still need docker  this link could be helpful.

Body:
I've tried to install docker cloud several months ago but I removed it. Now I have updated to Debian Stretch from Jessie and I get this error when I update via "apt-get update" and don't know how to solve it. Can anyone offer some help? Thanks!

sudo apt-get update
Get:1 http://debian.mirrors.ovh.net/debian stretch-updates InRelease
Ign:2 http://debian.mirrors.ovh.net/debian stretch InRelease
Get:3 http://repo.cloud.docker.com/ubuntu dockercloud InRelease [1,383 B]
Get:4 http://debian.mirrors.ovh.net/debian stretch Release
Hit:5 https://deb.nodesource.com/node_6.x jessie InRelease
Hit:6 https://apt.dockerproject.org/repo debian-stretch InRelease
Hit:7 http://security.debian.org stretch/updates InRelease
Ign:8 http://download.draios.com/stable/deb stable-amd64/ InRelease
Hit:9 http://download.draios.com/stable/deb stable-amd64/ Release
Ign:3 http://repo.cloud.docker.com/ubuntu dockercloud InRelease
Fetched 203 kB in 0s (247 kB/s)
Reading package lists... Done
W: GPG error: http://repo.cloud.docker.com/ubuntu dockercloud InRelease: The following signatures were invalid: 278FE7333CFF7F8B60B677E85DD27147EF170D1C
W: The repository 'http://repo.cloud.docker.com/ubuntu dockercloud InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Body:
W: GPG error: http://repo.cloud.docker.com/ubuntu dockercloud InRelease: The following signatures were invalid: 278FE7333CFF7F8B60B677E85DD27147EF170D1C
W: The repository 'http://repo.cloud.docker.com/ubuntu dockercloud InRelease' is not signed.

Actually this is a Warning not an Error.
It seems that somewhere in Your SourcesList(e.g. /etc/apt/sources.list) You still have a docker repo.

$ sudo grep -w "docker.com" /etc/apt/*.*

will show where is docker's url. If You do not need it any more, just comment this line.

Well, if You still need docker  this link could be helpful.


问:
Compatibility of ModSecurity with NginX
I'm using NginX and want to incorporate ModSec as a module. After doing some research, there only was one link that talked about how "ModSecurity must be compiled with the source code of the main server." I'm assuming that means it needs to compiled with Apache? (not really sure since I'm new to this)

Is ModSec compatible with NginX?

Are there an alternative to ModSec if not?

Please provide insights/links if possible!

Thanks!

Update Answer from ModSec lead developer:

This implementation contains 3 parts, ModSec, NginX, and a ModSec-NginX connector.

tutorial can be found here for Ubuntu 16.04: [link]https://www.howtoforge.com/tutorial/nginx-with-libmodsecurity-and-owasp-modsecurity-core-rule-set-on-ubuntu-1604/

PS. make sure when you're download the latest stable code for NginX

答:
ModSec not compatible with NginX

but there some rules you can set at  fastcgi_params that will help

```<code>location ~* union.*select.*\( {    deny all; }
location ~* union.*all.*select.* {   deny all; }
location ~* concat.*\( {   deny all; }
## Block common exploits
location ~* (<|%3C).*script.*(>|%3E) {   deny all; }
location ~* base64_(en|de)code\(.*\) {   deny all; }
location ~* (%24&x) {   deny all; }
location ~* (%0|%A|%B|%C|%D|%E|%F|127\.0) {   deny all; }
location ~* \.\.\/  {   deny all; }
location ~* ~$ {   deny all; }
location ~* proc/self/environ {   deny all; }
location ~* /\.(htaccess|htpasswd|svn) {   deny all; }
## Block file injections
location ~* [a-zA-Z0-9_]=(\.\.//?)+ {   deny all; }
location ~* [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ {   deny all; }
## wordpress security
location ~* wp-config.php {   deny all; }
location ~* wp-admin/includes {   deny all; }
location ~* wp-app\.log {   deny all; }
location ~* (licence|readme|license)\.(html|txt) {   deny all; }

 set $block_common_status 0;
    if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
        set $block_common_status 1;
    }
    if ($query_string ~ "base64_(en|de)code\(.*\)") {
        set $block_common_status 1;
    }
    if ($block_common_status = 1) {
        return 403;
    }

 if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) )
     {
         # return 404;
         return 403;
     }

    ## Block SQL injections
    set $block_sql_injections 0;
    if ($query_string ~ "union.*select.*\(") {
        set $block_sql_injections 1;
    }
    if ($query_string ~ "union.*all.*select.*") {
        set $block_sql_injections 1;
    }
    if ($query_string ~ "concat.*\(") {
        set $block_sql_injections 1;
    }
    if ($block_sql_injections = 1) {
        return 403;
    }

    ## Block file injections
    set $block_file_injections 0;
    if ($query_string ~ "[a-zA-Z0-9_]=http://") {
        set $block_file_injections 1;
    }
    if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") {
        set $block_file_injections 1;
    }
    if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") {
        set $block_file_injections 1;
    }
    if ($block_file_injections = 1) {
        return 403;
    }

    ## Block common exploits
    set $block_common_exploits 0;
    if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "proc/self/environ") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "base64_(en|de)code\(.*\)") {
        set $block_common_exploits 1;
    }
    if ($block_common_exploits = 1) {
        return 403;
    }

    ## Block spam
    set $block_spam 0;
    if ($query_string ~ "\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b") {
        set $block_spam 1;
    }
    if ($block_spam = 1) {
        return 403;
    }

    ## Block user agents
    set $block_user_agents 0;

    # Disable Akeeba Remote Control 2.5 and earlier
    if ($http_user_agent ~ "Indy Library") {
        set $block_user_agents 1;
    }

    # Common bandwidth hoggers and hacking tools.
    if ($http_user_agent ~ "libwww-perl") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GetRight") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GetWeb!") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Go!Zilla") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Download Demon") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Go-Ahead-Got-It") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "TurnitinBot") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GrabNet") {
        set $block_user_agents 1;
    }

    if ($block_user_agents = 1) {
        return 403;
    }
</code>```

Title: Compatibility of ModSecurity with NginX

Body:
ModSec not compatible with NginX

but there some rules you can set at  fastcgi_params that will help

location ~* union.*select.*\( {    deny all; }
location ~* union.*all.*select.* {   deny all; }
location ~* concat.*\( {   deny all; }
## Block common exploits
location ~* (<|%3C).*script.*(>|%3E) {   deny all; }
location ~* base64_(en|de)code\(.*\) {   deny all; }
location ~* (%24&x) {   deny all; }
location ~* (%0|%A|%B|%C|%D|%E|%F|127\.0) {   deny all; }
location ~* \.\.\/  {   deny all; }
location ~* ~$ {   deny all; }
location ~* proc/self/environ {   deny all; }
location ~* /\.(htaccess|htpasswd|svn) {   deny all; }
## Block file injections
location ~* [a-zA-Z0-9_]=(\.\.//?)+ {   deny all; }
location ~* [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ {   deny all; }
## wordpress security
location ~* wp-config.php {   deny all; }
location ~* wp-admin/includes {   deny all; }
location ~* wp-app\.log {   deny all; }
location ~* (licence|readme|license)\.(html|txt) {   deny all; }

 set $block_common_status 0;
    if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
        set $block_common_status 1;
    }
    if ($query_string ~ "base64_(en|de)code\(.*\)") {
        set $block_common_status 1;
    }
    if ($block_common_status = 1) {
        return 403;
    }

 if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) )
     {
         # return 404;
         return 403;
     }

    ## Block SQL injections
    set $block_sql_injections 0;
    if ($query_string ~ "union.*select.*\(") {
        set $block_sql_injections 1;
    }
    if ($query_string ~ "union.*all.*select.*") {
        set $block_sql_injections 1;
    }
    if ($query_string ~ "concat.*\(") {
        set $block_sql_injections 1;
    }
    if ($block_sql_injections = 1) {
        return 403;
    }

    ## Block file injections
    set $block_file_injections 0;
    if ($query_string ~ "[a-zA-Z0-9_]=http://") {
        set $block_file_injections 1;
    }
    if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") {
        set $block_file_injections 1;
    }
    if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") {
        set $block_file_injections 1;
    }
    if ($block_file_injections = 1) {
        return 403;
    }

    ## Block common exploits
    set $block_common_exploits 0;
    if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "proc/self/environ") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") {
        set $block_common_exploits 1;
    }
    if ($query_string ~ "base64_(en|de)code\(.*\)") {
        set $block_common_exploits 1;
    }
    if ($block_common_exploits = 1) {
        return 403;
    }

    ## Block spam
    set $block_spam 0;
    if ($query_string ~ "\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b") {
        set $block_spam 1;
    }
    if ($query_string ~ "\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b") {
        set $block_spam 1;
    }
    if ($block_spam = 1) {
        return 403;
    }

    ## Block user agents
    set $block_user_agents 0;

    # Disable Akeeba Remote Control 2.5 and earlier
    if ($http_user_agent ~ "Indy Library") {
        set $block_user_agents 1;
    }

    # Common bandwidth hoggers and hacking tools.
    if ($http_user_agent ~ "libwww-perl") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GetRight") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GetWeb!") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Go!Zilla") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Download Demon") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "Go-Ahead-Got-It") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "TurnitinBot") {
        set $block_user_agents 1;
    }
    if ($http_user_agent ~ "GrabNet") {
        set $block_user_agents 1;
    }

    if ($block_user_agents = 1) {
        return 403;
    }


问:
About mobile game porting
I would like to ask a few questions regarding mobile game porting...

Let say if I have a simple 2D C++ game engine and have a PC game based on that engine and I want to port it to different mobile platforms BREW, J2ME, iPhone, Android, Symbian, etc..

Do I need to re-code the engine and the game for each platform? or is there an easier and more efficient way? I am sure the process is complicated since different phones have different graphic/processor/memory/etc. I am just curious about the overview of mobile game porting process. :)

Thanks!

答:
As others have pointed out, if your engine is built on top of some 'platform independent' framework such as Java, then it's supposedly easier than if it's written in a lower level language. However, neither Java nor Flash is, for example, supported on the iPhone/iPod touch, and it'll probably take a while until they are. On the other hand, if I recall correctly, the only SDK available for those platforms is Objective-C, which, guessing wildly, you didn't use to implement your engine.

In general, it depends on the application/game engine you've written. Most likely you'll have to change something, as very rarely are all features available on all platforms. J2ME graphics is a classic scenario of 'platform independent'-dependence, or so I've heard. How much you'll have to change solely depends on how portable your code is, i.e. how well did you separate out the parts that potentially need changing.

Unfortunately, this is the best answer I can give you.

ContentLicense: CC BY-SA 2.5

Title: About mobile game porting

OwnerDisplayName: roe


问:
bubble sort for linked list in c++
i tried to implement buble sort for my university project and i have some problems.
i will be happy if you can help me with it.

```<code>void TrainManagerLinkedList:: Swap(TrainManager & x,TrainManager & y)
 {
  TrainManager temp;
  temp =x;
  x = y;
  y = temp;
 }

void TrainManagerLinkedList::BubbleSort()
 {
  TrainManagerLink* outerCurr = this->m_head;
  TrainManagerLink* curr = NULL;

  while(outerCurr != NULL)
  {
   curr = this->m_head;
   while(curr != NULL && curr->m_next != NULL)
   {
    /*if the current link greater then the next swap between them*/
    if (curr->m_data->GetDate() > curr->m_next->m_data->GetDate())
    {
     Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    else if((curr->m_data->GetDate() == curr->m_next->m_data->GetDate())&(curr->m_data->GetTime() > curr->m_next->m_data->GetTime()))
    {
      Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    curr = curr->m_next;
   }
   outerCurr = outerCurr->m_next;
  }
  /*now the list is sorted :)*/

 }
</code>```

my data types

```<code>TrainManagerLink *m_head;
 TrainManagerLink *m_tail;
 int m_numOfElements;

class TrainManager
{
 char * m_firstStation;
 char *m_lastStation;
 char * m_origin;
 char * m_destination;
 int m_timeBetweenStations;
 Hour m_releaseTime;
 Hour m_arriveTime;
 Hour m_firstHour;
 Date m_Date;
 int m_standInstation;
 DelayersLinkedList delay;
}
</code>```

the linked list should be sorted by date and hour.
but i have some compile problems.
i relly need your help
thank you,:)

答:
The compiler error is quite obvious.
Use Swap(*(curr->m_data),*(curr->m_next->m_data));
 instead of Swap(&(curr->m_data),&(curr->m_next->m_data));.

Title: bubble sort for linked list in c++

Body:
i tried to implement buble sort for my university project and i have some problems.
i will be happy if you can help me with it.

void TrainManagerLinkedList:: Swap(TrainManager & x,TrainManager & y)
 {
  TrainManager temp;
  temp =x;
  x = y;
  y = temp;
 }

void TrainManagerLinkedList::BubbleSort()
 {
  TrainManagerLink* outerCurr = this->m_head;
  TrainManagerLink* curr = NULL;

  while(outerCurr != NULL)
  {
   curr = this->m_head;
   while(curr != NULL && curr->m_next != NULL)
   {
    /*if the current link greater then the next swap between them*/
    if (curr->m_data->GetDate() > curr->m_next->m_data->GetDate())
    {
     Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    else if((curr->m_data->GetDate() == curr->m_next->m_data->GetDate())&(curr->m_data->GetTime() > curr->m_next->m_data->GetTime()))
    {
      Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    curr = curr->m_next;
   }
   outerCurr = outerCurr->m_next;
  }
  /*now the list is sorted :)*/

 }

my data types

TrainManagerLink *m_head;
 TrainManagerLink *m_tail;
 int m_numOfElements;

class TrainManager
{
 char * m_firstStation;
 char *m_lastStation;
 char * m_origin;
 char * m_destination;
 int m_timeBetweenStations;
 Hour m_releaseTime;
 Hour m_arriveTime;
 Hour m_firstHour;
 Date m_Date;
 int m_standInstation;
 DelayersLinkedList delay;
}

the linked list should be sorted by date and hour.
but i have some compile problems.
i relly need your help
thank you,:)


问:
Javascript loop through array asynchronous
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

```<code>function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}
</code>```

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.

答:
Here's another way that you could play with this. This way focuses more on the callback style, although it does assume that you can modify the scaffoldTo function, as well as the parameters required for digSchedule

```<code>function digSchedule(i, callback) {
   if(!i){
      i = 0;
   }
   if(i < blocksToMine.length){
      scaffoldTo(blocksToMine[i], digSchedule(i++, callback));
   }
   else{
     callback();
   }
}
</code>```

Then inside of scaffoldTo you would need something like this

```<code>function scaffoldTo(block, callback){
    //do what ever you need to have the bot go to the vector
    //after bot goes to vector call callback
    callback();
}
</code>```

In order to start it all you would just need to call digSchedule with something like this:

```<code>digSchedule({null or 0}, function(){
   console.log("finished visiting vectors");
});
</code>```

This does change the pattern from using a for loop like you have, but I think its a fun way to accomplish the goal as well.

Body:
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.

Body:
Here's another way that you could play with this. This way focuses more on the callback style, although it does assume that you can modify the scaffoldTo function, as well as the parameters required for digSchedule

function digSchedule(i, callback) {
   if(!i){
      i = 0;
   }
   if(i < blocksToMine.length){
      scaffoldTo(blocksToMine[i], digSchedule(i++, callback));
   }
   else{
     callback();
   }
}

Then inside of scaffoldTo you would need something like this

function scaffoldTo(block, callback){
    //do what ever you need to have the bot go to the vector
    //after bot goes to vector call callback
    callback();
}

In order to start it all you would just need to call digSchedule with something like this:

digSchedule({null or 0}, function(){
   console.log("finished visiting vectors");
});

This does change the pattern from using a for loop like you have, but I think its a fun way to accomplish the goal as well.


问:
Using apply() with a custom function and a second data frame
I'm trying to generate predicted values from a large number of model simulations and I'm having a hard time doing it simply. I suspect I need something from the apply() family, but I can't figure out the syntax.  Maybe my knowledge of apply() is weak. Or maybe my function is wrong.  Any suggestions?

Suppose I've got following coefficients resulting from six model simulations...

```<code>coef <- data.frame(intercept=c(2,3,5,7,2,1),
                   b1 = c(.2,.5,.6,.7,.9,.4),
                   b2 = c(10,11,12,11,9,10))
</code>```

I want to compute (predicted values or) the linear combination of each row above and each row of the following data frame...

```<code>df <- data.frame(age = c(50,20,19, 42),
                 height = c(60,72,79, 66))
</code>```

...Using the following model equation:

```<code>coef$intercept + coef$b1*df$age + coef$b2*df$height
</code>```

Done right, I should get the following 24 data values:

```<code>612.0   726.0   795.8   670.4
688.0   805.0   881.5   750
755.0   881.0   964.4   822.2
702.0   813.0   889.3   762.4
587.0   668.0   730.1   633.8
621.0   729.0   798.6   677.8
</code>```

To get the above, I've tried the following function and use of apply()...

```<code>equation <-  function(...) coef$intercept + coef$b1*df$age + coef$b2*df$height
result <- apply(df, 1, equation)
</code>```

...but I don't get the correct answer. The "result" data frame just repeats the correct diagonals. I also get the message:

```<code>> Warning messages: 1: In coef$b1 * df$age :   longer object length is
> not a multiple of shorter object length
</code>```

Yes I can get the correct answer through simple matrix multiplication:

```<code>df$ones <- 1
df <- df[,c(3, 1, 2)]
result <- as.matrix(coef) %*% t(as.matrix(df))
</code>```

But it seems to me one ought to be able to do this more generally using apply() and a custom function. Use of apply() is more compact and puts me less at risk of having my matrix columns in the wrong order.  Any suggestions?

Body:
I'm trying to generate predicted values from a large number of model simulations and I'm having a hard time doing it simply. I suspect I need something from the apply() family, but I can't figure out the syntax.  Maybe my knowledge of apply() is weak. Or maybe my function is wrong.  Any suggestions?

Suppose I've got following coefficients resulting from six model simulations...

coef <- data.frame(intercept=c(2,3,5,7,2,1),
                   b1 = c(.2,.5,.6,.7,.9,.4),
                   b2 = c(10,11,12,11,9,10))

I want to compute (predicted values or) the linear combination of each row above and each row of the following data frame...

df <- data.frame(age = c(50,20,19, 42),
                 height = c(60,72,79, 66))

...Using the following model equation:

coef$intercept + coef$b1*df$age + coef$b2*df$height

Done right, I should get the following 24 data values:

612.0   726.0   795.8   670.4
688.0   805.0   881.5   750
755.0   881.0   964.4   822.2
702.0   813.0   889.3   762.4
587.0   668.0   730.1   633.8
621.0   729.0   798.6   677.8

To get the above, I've tried the following function and use of apply()...

equation <-  function(...) coef$intercept + coef$b1*df$age + coef$b2*df$height
result <- apply(df, 1, equation)

...but I don't get the correct answer. The "result" data frame just repeats the correct diagonals. I also get the message:

> Warning messages: 1: In coef$b1 * df$age :   longer object length is
> not a multiple of shorter object length

Yes I can get the correct answer through simple matrix multiplication:

df$ones <- 1
df <- df[,c(3, 1, 2)]
result <- as.matrix(coef) %*% t(as.matrix(df))

But it seems to me one ought to be able to do this more generally using apply() and a custom function. Use of apply() is more compact and puts me less at risk of having my matrix columns in the wrong order.  Any suggestions?

Body:
If you really want to use apply, you can do this:

result<- t(apply(coef, 1, function(x) x[1] + x[2]*df$age + x[3]*df$height))
> result
     [,1] [,2]  [,3]  [,4]
[1,]  612  726 795.8 670.4
[2,]  688  805 881.5 750.0
[3,]  755  881 964.4 822.2
[4,]  702  813 889.3 762.4
[5,]  587  668 730.1 633.8
[6,]  621  729 798.6 677.8

But it's really preferable (and faster) to do the matrix multiplication.


问:
Python thread management modules
what is the best module in python for multi thread management ?

1.Create N number of threads
   2.Assigning work to thread if it is free
   3.Getting the status of the thread
   4.killing a thread

答:
You could use the threading module.

https://docs.python.org/3/library/threading.html#module-threading

You could also use concurrent.futures

https://docs.python.org/3/library/concurrent.futures.html

Keep in mind that Python doesn't support true threading because of the global interpreter lock. As a result you would typically use threading for IO bound tasks.

https://wiki.python.org/moin/GlobalInterpreterLock

If you could be a little more specific with what you are trying to accomplish in # 1-4 I could give an applicable example.

Title: Python thread management modules


问:
Python GUI without 'video system'
I'm currently at a crossroads. I'm somewhat versed in Python (2.7) and would really like to start getting into GUI to give my (although mini) projects some more depth and versibility.

For the most part, my scripts don't use anything graphical so this is the first time I'm dipping my toes in this water.

That said, I've tried using pygame and tkinter but seem to fail at every turn to get something up and running (although I had some slight success with pygame)

Am I correct to understand that for both I need X started in order to generate any type of interface, and with that, so I need X to get any type of input (touchscreen presses)?

Thanks in advance!

答:
I'm gonna give an alternative answer. If you know HTML, CSS and Javascript (or have time to give it a try) I would recommend using Flask, http://flask.pocoo.org/.

With flask you can create websites but you can also (as I am using it) let it be your GUI. It will work on any device and looks really good :).

Title: Python GUI without 'video system'