问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答:
Either this works your compiler/hardware is bugged.</p>

```<code>k = 0;

for (i=0; i < nrow; i++) {
    dat[k++] = 1.0f;
}

printf("%d, %d", dat[0], dat[nrow - 1]);
</code>```

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit

Body:
Either this works your compiler/hardware is bugged.

k = 0;

for (i=0; i < nrow; i++) {
    dat[k++] = 1.0f;
}

printf("%d, %d", dat[0], dat[nrow - 1]);


来源: stackexchange

问:
Possible tail recursive solution in haskell producing stack overflow
I've been trying to solve the adventofcode day 5 question 2 (https://adventofcode.com/2017/day/5). It differs from the first question where if the item is bigger of equal to 3, it's decreased instead of increased by 1.

When running the implementation with the test data, it produces the correct outcome, so it seems that the implementation is perfect. Also, the recursive call looks to be in tail position, but it's still producing a stackoverflow exception.

The code looks like this

```<code>module AdventOfCode5 where

type Instruction = Int
type Position = Int

main :: IO ()
main = do
  input <- readFile "day5input.txt"
  let instructions = fmap (read :: String -> Instruction) $ lines input
  _ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 (+1) $ instructions
  return ()

main2 :: IO ()
main2 = do
  input <- readFile "day5input.txt"
  let instructions = fmap (read :: String -> Instruction) $ lines input
  _ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 decAbove3AndIncBelow3 instructions
  return ()

decAbove3AndIncBelow3 :: Int -> Int
decAbove3AndIncBelow3 x
  | x >= 3 = x - 1
  | otherwise = x + 1

computeResult :: Int -> Position -> (Int -> Int) -> [Instruction] -> Int
computeResult = takeStep' 0
  where takeStep' :: Int -> Int -> Position -> (Int -> Int) -> [Instruction] -> Int
        takeStep' count max pos changeInteger instructions
          | pos >= max = count
          | otherwise =
              let
                elementAtPos = instructions!!pos
                newCount = count + 1
                newPos = pos + elementAtPos
                newInstructions = (take pos instructions) ++ ([(changeInteger elementAtPos)]) ++ (drop (pos + 1)) instructions
              in
                takeStep' newCount max newPos changeInteger newInstructions
</code>```

The idea of the implementation is that you hold a counter and increment the counter for every iteration, in combination with altering the list of instructions with the updated version (where the Int -> Int is the function that knows how to update). You got a position where to look at and the recursion stops as soon as the position is larger than the list size (which i passed as input but could also be derived from the list of instructions).

Can anybody explain to me why this one is producing a stackoverflow?

答:
There is a space leak in the first argument of takeStep', because it builds a thunk (... ((0 + 1) + 1) ...) + 1 instead of just evaluating the integer.

The stack may explode when that thunk gets evaluated.

Use seq to force count before continuing, e.g., count `seq` otherwise in the guard;

or compile with optimizations.

ghci is interpreting it, not compiling it. In particular, it doesn't perform the strictness analysis necessary to automatically fix that leak.

You can run this command to compile with optimizations (-O)

```<code>ghc -O -main-is AdventOfCode5.main2 AdventOfCode5.hs
</code>```

(although even without optimizations compilation seems to reduce space usage enough to succeed.)

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to solve the adventofcode day 5 question 2 (https://adventofcode.com/2017/day/5). It differs from the first question where if the item is bigger of equal to 3, it's decreased instead of increased by 1.

When running the implementation with the test data, it produces the correct outcome, so it seems that the implementation is perfect. Also, the recursive call looks to be in tail position, but it's still producing a stackoverflow exception.

The code looks like this

module AdventOfCode5 where

type Instruction = Int
type Position = Int

main :: IO ()
main = do
  input <- readFile "day5input.txt"
  let instructions = fmap (read :: String -> Instruction) $ lines input
  _ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 (+1) $ instructions
  return ()

main2 :: IO ()
main2 = do
  input <- readFile "day5input.txt"
  let instructions = fmap (read :: String -> Instruction) $ lines input
  _ <- putStrLn $ show $ computeResult (Prelude.length instructions) 0 decAbove3AndIncBelow3 instructions
  return ()

decAbove3AndIncBelow3 :: Int -> Int
decAbove3AndIncBelow3 x
  | x >= 3 = x - 1
  | otherwise = x + 1

computeResult :: Int -> Position -> (Int -> Int) -> [Instruction] -> Int
computeResult = takeStep' 0
  where takeStep' :: Int -> Int -> Position -> (Int -> Int) -> [Instruction] -> Int
        takeStep' count max pos changeInteger instructions
          | pos >= max = count
          | otherwise =
              let
                elementAtPos = instructions!!pos
                newCount = count + 1
                newPos = pos + elementAtPos
                newInstructions = (take pos instructions) ++ ([(changeInteger elementAtPos)]) ++ (drop (pos + 1)) instructions
              in
                takeStep' newCount max newPos changeInteger newInstructions

The idea of the implementation is that you hold a counter and increment the counter for every iteration, in combination with altering the list of instructions with the updated version (where the Int -> Int is the function that knows how to update). You got a position where to look at and the recursion stops as soon as the position is larger than the list size (which i passed as input but could also be derived from the list of instructions).

Can anybody explain to me why this one is producing a stackoverflow?

Body:
There is a space leak in the first argument of takeStep', because it builds a thunk (... ((0 + 1) + 1) ...) + 1 instead of just evaluating the integer.

The stack may explode when that thunk gets evaluated.

Use seq to force count before continuing, e.g., count `seq` otherwise in the guard;

or compile with optimizations.

ghci is interpreting it, not compiling it. In particular, it doesn't perform the strictness analysis necessary to automatically fix that leak.

You can run this command to compile with optimizations (-O)

ghc -O -main-is AdventOfCode5.main2 AdventOfCode5.hs

(although even without optimizations compilation seems to reduce space usage enough to succeed.)


问:
C++ if a pointer point to nullptr, can I replace it with number?

Hey guys, I encountered some problems about C++. Actually it's not the problem of language feature, otherwise it is related to kind of coding style.

OK, Let's get to the point!

I try to write the AVL Tree and want to calculate the balance factors,
and according the rule, the subtree without nodes(just a empty tree),
its height should be treated as -1. Yeah, everything thinks fine,
but when I write the code, use pointer to read Node class member,
I cannot read the nullptr BAD ACCESS, so I add lots of conditions, which makes my code look bad. Here is some parts of my code.

```<code>struct Node{
    int key;
    int height;
    Node* left;
    Node* right;
    Node* parent;
    Node(void);
    Node(int key);
};

    while((parent_node->left->height - parent_node->right->height) <= 1
          ||(parent_node->left->height - parent_node->right->height) >= (-1))
    {
        parent_node = parent_node->parent;
        if(parent_node == nullptr) break;
    }
</code>```

The result I want is that when the parent_node's left subtree is empty,
its height will be treated as -1. And the fact is, though it's empty, its height should not exist.
So in the code I only list four cases

1. left subtree == nullptr && right subtree == nullptr

2. left subtree != nullptr && right subtree == nullptr

3. left subtree != nullptr && right subtree != nullptr

4. left subtree == nullptr && right subtree != nullptr

Then I replace the code of height part with the value -1 respectively.
It feels painful. And this condition happens in my coding time many times, I want to find the better solution.

My English is not that good, so my description maybe sort of misleading, I will appreciate it if you help me in any way.

答: Unless I misunderstand, you could point to a sentinel node in stead of null as the terminator link. Set the height of the sentinel to -1 and it doesn't need to be handled differently for that part of the algorithm.</p>

Body:
Hey guys, I encountered some problems about C++. Actually it's not the problem of language feature, otherwise it is related to kind of coding style.

OK, Let's get to the point!

I try to write the AVL Tree and want to calculate the balance factors,
and according the rule, the subtree without nodes(just a empty tree),
its height should be treated as -1. Yeah, everything thinks fine,
but when I write the code, use pointer to read Node class member,
I cannot read the nullptr BAD ACCESS, so I add lots of conditions, which makes my code look bad. Here is some parts of my code.

struct Node{
    int key;
    int height;
    Node* left;
    Node* right;
    Node* parent;
    Node(void);
    Node(int key);
};

    while((parent_node->left->height - parent_node->right->height) <= 1
          ||(parent_node->left->height - parent_node->right->height) >= (-1))
    {
        parent_node = parent_node->parent;
        if(parent_node == nullptr) break;
    }

The result I want is that when the parent_node's left subtree is empty,
its height will be treated as -1. And the fact is, though it's empty, its height should not exist.
So in the code I only list four cases

1. left subtree == nullptr && right subtree == nullptr

2. left subtree != nullptr && right subtree == nullptr

3. left subtree != nullptr && right subtree != nullptr

4. left subtree == nullptr && right subtree != nullptr

Then I replace the code of height part with the value -1 respectively.
It feels painful. And this condition happens in my coding time many times, I want to find the better solution.

My English is not that good, so my description maybe sort of misleading, I will appreciate it if you help me in any way.


问:
TextView is not showing in an Activity
I have an Activity that has some elements such as ImageViews, TextViews, EditTexts and Buttons. Everything is showing OK but two TextViews are not visible when I run the app. The preview is OK but when I open the app in my phone it doesn't show.

This is my XML code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context="com.construct.v2.activities.auth.PasswordChangeActivity">
  <!--<include android:id="@+id/toolbar" layout="@layout/toolbar_simple" />-->
  <ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/mm_margin"
    android:layout_gravity="center"
    android:visibility="gone"/>

  <RelativeLayout
      android:id="@+id/contentLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:paddingLeft="24dp"
      android:paddingRight="24dp"
      android:paddingTop="80dp">
    <ImageView
        android:id="@+id/change_lock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/change_pass"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:fontFamily="sans-serif-medium"
        android:textStyle="normal"
        android:textColor="#00596f"
        android:lineSpacingExtra="2sp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/change_lock"
        tools:text="@string/change_password"
        />

    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:fontFamily="sans-serif"
        android:textStyle="normal"
        android:textColor="#555555"
        android:lineSpacingExtra="4sp"
        android:layout_below="@+id/title"
        android:layout_centerHorizontal="true"
        android:paddingTop="15dp"
        tools:text="@string/new_password_text"
        />

    <TextView
        android:id="@+id/fill_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/subtitle"
        android:textColor="@color/construct_red"
        android:paddingTop="15dp"
        />

    <EditText
          android:id="@+id/password"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="@string/password"
          android:textSize="16dp"
          android:textColorHint="#b1b1b1"
          android:layout_below="@+id/fill_password"
          android:backgroundTint="#00596f"
          android:textColor="#00596f"
          android:textCursorDrawable="@drawable/color_cursor"
          android:inputType="textPassword"
          />
    <Button
        android:id="@+id/saveButton"
        android:layout_width="220dp"
        android:layout_height="40dp"
        android:text="@string/save"
        android:textSize="14dp"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textColor="#b1b1b1"
        android:background="#e3e3e3"
        android:paddingLeft="56dp"
        android:paddingRight="56dp"
        android:layout_below="@+id/password"
        android:layout_marginTop="32dp"/>
  </RelativeLayout>
</RelativeLayout>
</code>```

This is the preview from Android Studio:

And this is the app running in my phone:

答:
I just found the problem. I am using Zeplin as a tool for screen designing and it usually generates the XML code for the elements. Instead of:

```<code>tools:text="@string/new_password_text"
</code>```

I changed to:

```<code>android:text="@string/new_password_text"
</code>```

Title: TextView is not showing in an Activity

Body:
I have an Activity that has some elements such as ImageViews, TextViews, EditTexts and Buttons. Everything is showing OK but two TextViews are not visible when I run the app. The preview is OK but when I open the app in my phone it doesn't show.

This is my XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context="com.construct.v2.activities.auth.PasswordChangeActivity">

  <ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/mm_margin"
    android:layout_gravity="center"
    android:visibility="gone"/>

  <RelativeLayout
      android:id="@+id/contentLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:paddingLeft="24dp"
      android:paddingRight="24dp"
      android:paddingTop="80dp">
    <ImageView
        android:id="@+id/change_lock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/change_pass"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:fontFamily="sans-serif-medium"
        android:textStyle="normal"
        android:textColor="#00596f"
        android:lineSpacingExtra="2sp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/change_lock"
        tools:text="@string/change_password"
        />

    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:fontFamily="sans-serif"
        android:textStyle="normal"
        android:textColor="#555555"
        android:lineSpacingExtra="4sp"
        android:layout_below="@+id/title"
        android:layout_centerHorizontal="true"
        android:paddingTop="15dp"
        tools:text="@string/new_password_text"
        />

    <TextView
        android:id="@+id/fill_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/subtitle"
        android:textColor="@color/construct_red"
        android:paddingTop="15dp"
        />

    <EditText
          android:id="@+id/password"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="@string/password"
          android:textSize="16dp"
          android:textColorHint="#b1b1b1"
          android:layout_below="@+id/fill_password"
          android:backgroundTint="#00596f"
          android:textColor="#00596f"
          android:textCursorDrawable="@drawable/color_cursor"
          android:inputType="textPassword"
          />
    <Button
        android:id="@+id/saveButton"
        android:layout_width="220dp"
        android:layout_height="40dp"
        android:text="@string/save"
        android:textSize="14dp"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textColor="#b1b1b1"
        android:background="#e3e3e3"
        android:paddingLeft="56dp"
        android:paddingRight="56dp"
        android:layout_below="@+id/password"
        android:layout_marginTop="32dp"/>
  </RelativeLayout>
</RelativeLayout>

This is the preview from Android Studio:

And this is the app running in my phone:

Body:
I just found the problem. I am using Zeplin as a tool for screen designing and it usually generates the XML code for the elements. Instead of:

tools:text="@string/new_password_text"

I changed to:

android:text="@string/new_password_text"


问:
Modelbinding an optional array of a custom model bound type
I'm stuck with binding an optional array in an ASP.NET Core Controller. The array contains elements of a custom type. Single elements of this type are bound with a custom model binder and validated in it.

Sample repo here: https://github.com/MarcusKohnert/OptionalArrayModelBinding

I get only two tests out of three working in the sample test project:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/blob/master/OptionalArrayModelBindingTest/TestOptionalArrayCustomModelBinder.cs

```<code>public class TestOptionalArrayCustomModelBinder
{
    private readonly TestServer server;
    private readonly HttpClient client;

    public TestOptionalArrayCustomModelBinder()
    {
        server = new TestServer(new WebHostBuilder().UseStartup<Startup>());

        client = server.CreateClient();
    }

    [Fact]
    public async Task SuccessWithoutProvidingIds()
    {
        var response = await client.GetAsync("/api/values");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task SuccessWithValidIds()
    {
        var response = await client.GetAsync("/api/values?ids=aaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task FailureWithOneInvalidId()
    {
        var response = await client.GetAsync("/api/values?ids=xaaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
    }
}
</code>```

Controller:

```<code>[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public IActionResult Get(CustomIdentifier[] ids)
    {
        if (this.ModelState.IsValid == false) return this.BadRequest();

        return this.Ok(ids);
    }
}
</code>```

Startup:

```<code>public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new CutomIdentifierModelBinderProvider());
            //options.ModelBinderProviders.Add(new CutomIdentifierModelBinderProvider());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}
</code>```

ModelBinder:

```<code>public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        //if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        //{
        //    return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        //}

        if (context.Metadata.ModelType == typeof(CustomIdentifier))
        {
            return new BinderTypeModelBinder(typeof(CustomIdentifierModelBinder));
        }

        return null;
    }
}

public class CustomIdentifierModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
        var parseResult    = CustomIdentifier.TryParse(attemptedValue);

        if (parseResult.Failed)
        {
            bindingContext.Result = ModelBindingResult.Failed();
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, parseResult.Message.Message);
        }
        else
        {
            bindingContext.Model  = parseResult.Value;
            bindingContext.Result = ModelBindingResult.Success(parseResult.Value);
        }

        return Task.CompletedTask;
    }
}
</code>```

The MVC default ArrayModelBinder of T binds optional arrays correctly and sets ModelState.IsValid to true. If I use my own CustomIdentifierModelBinder however ModelState.IsValid will be false. Empty arrays are not recognized as valid.

How can I solve this problem? Thanks in advance.

答:
The solution is the following code change, reflected in this commit:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/commit/552f4d35d8c33c002e1aa0c05acb407f1f962102

I've found the solution by inspecting MVC's source code again.
https://github.com/aspnet/Mvc/blob/35601f95b345d0ef938fb21ce1c51f5a67a1fb62/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/SimpleTypeModelBinder.cs#L37

You'll need to check the valueProviderResult for None. If it's none then there is no parameter given and the ModelBinder binds correctly.

```<code>        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == ValueProviderResult.None)
</code>```

And also you register the provided ArrayModelBinder of T with your custom ModelBinder:

```<code>        if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        {
            return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        }
</code>```

Body:
I'm stuck with binding an optional array in an ASP.NET Core Controller. The array contains elements of a custom type. Single elements of this type are bound with a custom model binder and validated in it.

Sample repo here: https://github.com/MarcusKohnert/OptionalArrayModelBinding

I get only two tests out of three working in the sample test project:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/blob/master/OptionalArrayModelBindingTest/TestOptionalArrayCustomModelBinder.cs

public class TestOptionalArrayCustomModelBinder
{
    private readonly TestServer server;
    private readonly HttpClient client;

    public TestOptionalArrayCustomModelBinder()
    {
        server = new TestServer(new WebHostBuilder().UseStartup<Startup>());

        client = server.CreateClient();
    }

    [Fact]
    public async Task SuccessWithoutProvidingIds()
    {
        var response = await client.GetAsync("/api/values");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task SuccessWithValidIds()
    {
        var response = await client.GetAsync("/api/values?ids=aaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task FailureWithOneInvalidId()
    {
        var response = await client.GetAsync("/api/values?ids=xaaa001&ids=bbb002");

        Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
    }
}

Controller:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpGet]
    public IActionResult Get(CustomIdentifier[] ids)
    {
        if (this.ModelState.IsValid == false) return this.BadRequest();

        return this.Ok(ids);
    }
}

Startup:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new CutomIdentifierModelBinderProvider());
            //options.ModelBinderProviders.Add(new CutomIdentifierModelBinderProvider());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

ModelBinder:

public class CutomIdentifierModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        //if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        //{
        //    return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        //}

        if (context.Metadata.ModelType == typeof(CustomIdentifier))
        {
            return new BinderTypeModelBinder(typeof(CustomIdentifierModelBinder));
        }

        return null;
    }
}

public class CustomIdentifierModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var attemptedValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
        var parseResult    = CustomIdentifier.TryParse(attemptedValue);

        if (parseResult.Failed)
        {
            bindingContext.Result = ModelBindingResult.Failed();
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, parseResult.Message.Message);
        }
        else
        {
            bindingContext.Model  = parseResult.Value;
            bindingContext.Result = ModelBindingResult.Success(parseResult.Value);
        }

        return Task.CompletedTask;
    }
}

The MVC default ArrayModelBinder of T binds optional arrays correctly and sets ModelState.IsValid to true. If I use my own CustomIdentifierModelBinder however ModelState.IsValid will be false. Empty arrays are not recognized as valid.

How can I solve this problem? Thanks in advance.

Body:
The solution is the following code change, reflected in this commit:
https://github.com/MarcusKohnert/OptionalArrayModelBinding/commit/552f4d35d8c33c002e1aa0c05acb407f1f962102

I've found the solution by inspecting MVC's source code again.
https://github.com/aspnet/Mvc/blob/35601f95b345d0ef938fb21ce1c51f5a67a1fb62/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/SimpleTypeModelBinder.cs#L37

You'll need to check the valueProviderResult for None. If it's none then there is no parameter given and the ModelBinder binds correctly.

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == ValueProviderResult.None)

And also you register the provided ArrayModelBinder of T with your custom ModelBinder:

        if (context.Metadata.ModelType.IsArray && context.Metadata.ModelType == typeof(CustomIdentifier[]))
        {
            return new ArrayModelBinder<CustomIdentifier>(new CustomIdentifierModelBinder());
        }


问:
python manipulating list after user input
```<code>months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if usermonth >=months[0]and usermonth <=months[10]:
   nextmonth=months(usermonth+1)
   print(nextmonth)
</code>```

How would I go about defining one up in the index of the user's month?
Thanks.

答:
I believe you want to print the next month, inserted by the user :

To do this, you need to have a better understanding of arrays, and indexing (or, said differently : how to access a list of data).

You properly used the indexing in your if-statement, but, you didn't in the line  trying to define nextMonth. Doing months() called the keyword months as if it is a function : and you need to call it as a list, and therefore, use an index, with []. :)

Body:
months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if usermonth >=months[0]and usermonth <=months[10]:
   nextmonth=months(usermonth+1)
   print(nextmonth)

How would I go about defining one up in the index of the user's month?
Thanks.


问:
return index of each element in list if it repeats
I was needed to find all indexes of elements if some part of element is repeated (all text without underscore and numbers).
I am really newbie in Python and that's why I am using following code:

```<code>import re
list = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']
list2 = []
for i in range(len(list)):
  list2.append(str(re.sub('[^a-z,A-Z]','', list[i])))

indexList = []
for i in range(len(list2)):
    if list2.count(list2[i]) > 1:
        indexList.append(i)

for i in range(len(indexList)):
    print(list[indexList[i]])
</code>```

May be you can provide me more elegant procedure ?

答:
```<code>import re

list1 = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']
list2 = list(set([''.join(filter(str.isalpha,s)) for s in list1]))
print (list2)
</code>```

=================================================

```<code>[''.join(filter(str.isalpha,s)) for s in list1] --> the list without numbers/special characters

list(set())-->removes the duplicate characters
</code>```

i hope this 1-liner helps!modified list to list1 so python will not get confused :)

Body:
I was needed to find all indexes of elements if some part of element is repeated (all text without underscore and numbers).
I am really newbie in Python and that's why I am using following code:

import re
list = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']
list2 = []
for i in range(len(list)):
  list2.append(str(re.sub('[^a-z,A-Z]','', list[i])))

indexList = []
for i in range(len(list2)):
    if list2.count(list2[i]) > 1:
        indexList.append(i)

for i in range(len(indexList)):
    print(list[indexList[i]])

May be you can provide me more elegant procedure ?

Body:
import re

list1 = ['Magnet_1' , 'Magnet_2' , 'Magnet_3']
list2 = list(set([''.join(filter(str.isalpha,s)) for s in list1]))
print (list2)

=================================================

[''.join(filter(str.isalpha,s)) for s in list1] --> the list without numbers/special characters

list(set())-->removes the duplicate characters

i hope this 1-liner helps!modified list to list1 so python will not get confused :)


问:
How to Retrieve JTable Data as an Array
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want to be able to load the new data back into an array (Object[][]). Note that I'd rather not just update the array bit by bit, but be able to just completely load a new array from the table. How can this be done?

答:
With the out-of-the-box JTable implementation, you can't. When you initialize a JTable with Object[][] rowData that rowData is used by an anonymous AbstractTableModel instance but it's not accesible as such from outside.

```<code>public JTable(final Object[][] rowData, final Object[] columnNames) {
    this(new AbstractTableModel() {
        public String getColumnName(int column) { return columnNames[column].toString(); }
        public int getRowCount() { return rowData.length; }
        public int getColumnCount() { return columnNames.length; }
        public Object getValueAt(int row, int col) { return rowData[row][col]; }
        public boolean isCellEditable(int row, int column) { return true; }
        public void setValueAt(Object value, int row, int col) {
            rowData[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    });
}
</code>```

You could consider to subclass both JTable and AbstractTableModel and "overwrite" this constructor in JTable to create your own TableModel implementation that will hold that Object[][] reference and return it with Object[][] getRowData(). Or just keep the rowData as a field in the JTable subclass itself after calling super(...) in that constructor -- if you don't really care about MVC.

But you need to make sure that after the table is edited, the initial model is preserved and not replaced by a new model object (of course, of a different type) with setModel. If this is the case, what you want is impossible to achieve -- you will need to iterate through all the cells.

Title: How to Retrieve JTable Data as an Array

Body:
With the out-of-the-box JTable implementation, you can't. When you initialize a JTable with Object[][] rowData that rowData is used by an anonymous AbstractTableModel instance but it's not accesible as such from outside.

public JTable(final Object[][] rowData, final Object[] columnNames) {
    this(new AbstractTableModel() {
        public String getColumnName(int column) { return columnNames[column].toString(); }
        public int getRowCount() { return rowData.length; }
        public int getColumnCount() { return columnNames.length; }
        public Object getValueAt(int row, int col) { return rowData[row][col]; }
        public boolean isCellEditable(int row, int column) { return true; }
        public void setValueAt(Object value, int row, int col) {
            rowData[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    });
}

You could consider to subclass both JTable and AbstractTableModel and "overwrite" this constructor in JTable to create your own TableModel implementation that will hold that Object[][] reference and return it with Object[][] getRowData(). Or just keep the rowData as a field in the JTable subclass itself after calling super(...) in that constructor -- if you don't really care about MVC.

But you need to make sure that after the table is edited, the initial model is preserved and not replaced by a new model object (of course, of a different type) with setModel. If this is the case, what you want is impossible to achieve -- you will need to iterate through all the cells.

ContentLicense: CC BY-SA 2.5


问:
Angular HostListener event from Child Component to Parent Component
I have two components - Parent and Child component.
I have attached hostlistener to both component to detect key events.
I want to detect space key event in both components. If user presses space key in child component text field then i want parent component to do nothing. But if user is not in child component text field and presses space key then i want parent component to trigger a function.

```<code>export class ParentComponent {

 constructor() { }

 @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
  console.log("PARENT", event.keyCode);
 }
}

export class ChildComponent {

 constructor() { }

 @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
  console.log("CHILD", event.keyCode);
 }
}
</code>```

Here events are getting captured but in specific order - first PARENT and then CHILD. What i want these events to be - first captured by CHILD so that i can decide what to do in parent component or can stop event propagation.

答:
If we add same listener event in both parent and child component there are two possibilities.

If user triggers from parent component, only the event in parent component will be executed

If user triggers from child component, both the events in child and parent component will be executed. remove window from listener events so child component will be executed first before the parent component.

If you don't want to execute parent from child, pass some variables to parent to control the events.

Working demo, I have used escape event as sample

Parent component

```<code>import { Component } from '@angular/core';
import {  HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  color : String='green';
  child : Boolean=true;

  @HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {

    if(e.keyCode===27 && this.child===true){
      console.log("global esc");
      alert("parent esc");
    }else{
      this.child=true;
    }
  }

  public doSomething(child: any):void {
    this.child=child;
}

  name = 'Angular 5';
}
</code>```

Parent template

```<code><input placeholder="Parent Can't copy/paste" type="text" appBlockCopyPaste/>
<hello (child)="doSomething($event)"></hello>
</code>```

Child component with template

```<code>import { Component, Input,Output , EventEmitter} from '@angular/core';
import {  HostListener } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<input placeholder="Child" type="text" appBlockCopyPaste/>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Output() child: EventEmitter<any> = new EventEmitter<any>();

  @HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {
    if(e.keyCode===27){
      this.child.emit(false);
      console.log("global esc");
      alert("child esc");
    }
  }
}
</code>```

Body:
I have two components - Parent and Child component.
I have attached hostlistener to both component to detect key events.
I want to detect space key event in both components. If user presses space key in child component text field then i want parent component to do nothing. But if user is not in child component text field and presses space key then i want parent component to trigger a function.

export class ParentComponent {

 constructor() { }

 @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
  console.log("PARENT", event.keyCode);
 }
}

export class ChildComponent {

 constructor() { }

 @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
  console.log("CHILD", event.keyCode);
 }
}

Here events are getting captured but in specific order - first PARENT and then CHILD. What i want these events to be - first captured by CHILD so that i can decide what to do in parent component or can stop event propagation.

Body:
If we add same listener event in both parent and child component there are two possibilities.

If user triggers from parent component, only the event in parent component will be executed

If user triggers from child component, both the events in child and parent component will be executed. remove window from listener events so child component will be executed first before the parent component.

If you don't want to execute parent from child, pass some variables to parent to control the events.

Working demo, I have used escape event as sample

Parent component

import { Component } from '@angular/core';
import {  HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  color : String='green';
  child : Boolean=true;

  @HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {

    if(e.keyCode===27 && this.child===true){
      console.log("global esc");
      alert("parent esc");
    }else{
      this.child=true;
    }
  }

  public doSomething(child: any):void {
    this.child=child;
}

  name = 'Angular 5';
}

Parent template

<input placeholder="Parent Can't copy/paste" type="text" appBlockCopyPaste/>
<hello (child)="doSomething($event)"></hello>

Child component with template

import { Component, Input,Output , EventEmitter} from '@angular/core';
import {  HostListener } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<input placeholder="Child" type="text" appBlockCopyPaste/>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Output() child: EventEmitter<any> = new EventEmitter<any>();

  @HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {
    if(e.keyCode===27){
      this.child.emit(false);
      console.log("global esc");
      alert("child esc");
    }
  }
}


问:
show Angular 4 project inside html div tag
I need to show my angular project(mentioned as http://test.com ) inside the div(.test). Is it possible to show angular project inside div  without using iframe, object and embed? .Here is my code .Any help would be amazing .Thanks in advance</p>

```<code><html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: 'http://test.com',  //Pass URL here
                type: "GET", //Also use GET method
                success: function (data) {
                    $('.test').html(data);
                }
            });
        });
    </script>

</head>
<body>

    <div> Div of base html</div>
    <div class="test"></div>

</body>

</html>
</code>```

答:
in your app.component.html you can put your <app-root></app-root> inside what you want:

<menu [menu]="menu" #sideMenu></menu>

  <app-root></app-root>

```

this is my app.component.html for example

Body:
I need to show my angular project(mentioned as http://test.com ) inside the div(.test). Is it possible to show angular project inside div  without using iframe, object and embed? .Here is my code .Any help would be amazing .Thanks in advance

 Div of base html

Body:
in your app.component.html you can put your <app-root></app-root> inside what you want:

<header (menuToggle)="sideMenu.toggle()"></header>
<menu [menu]="menu" #sideMenu></menu>
<div>
  <app-root></app-root>
</div>
<footer></footer>

this is my app.component.html for example


问:
Get value from another model in case of ManyToManyField
I want to get value from foreign key from another model and subscribe it.
It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works.
How can I do it?

Please help.

```<code>class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    language = models.ManyToManyField(Language, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.text = self.project.text                     #WORKS
        self.language  = self.project.language.all()      #NOT WORKS
        super(Document, self).save(*args, **kwargs)
</code>```

答:
You need to use .add() for initializing ManyToManyField

Change this line

```<code># use plural naming convention when its ManyToMany relation `language` should be `languages` in your Document model
self.language  = self.project.language.all()
</code>```

to

```<code># call save method of super class before adding values to many-to-many
super(Document, self).save(*args, **kwargs)
p_language = self.project.language.all()
self.language.add(*p_language)
</code>```

So you must call save before adding the many-to-many relationship. Since add immediately affects the database, you do not need to save afterwards.

Body:
I want to get value from foreign key from another model and subscribe it.
It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works.
How can I do it?

Please help.

class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    language = models.ManyToManyField(Language, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.text = self.project.text                     #WORKS
        self.language  = self.project.language.all()      #NOT WORKS
        super(Document, self).save(*args, **kwargs)

Body:
You need to use .add() for initializing ManyToManyField

Change this line

# use plural naming convention when its ManyToMany relation `language` should be `languages` in your Document model
self.language  = self.project.language.all()

to

# call save method of super class before adding values to many-to-many
super(Document, self).save(*args, **kwargs)
p_language = self.project.language.all()
self.language.add(*p_language)

So you must call save before adding the many-to-many relationship. Since add immediately affects the database, you do not need to save afterwards.


问:
JSON parse on a JSON string throws "Cannot convert object to primitive value"
server.js

uses the body parser middleware, handlebars and express

route

```<code>module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};
</code>```

client

```<code>function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

```<code>     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5
</code>```

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).

答:
dataType doesn't say what type of data you're sending, it says what type of response you expect. You need to say that you're sending JSON, via contentType: "application/json" in your ajax call. Details in the documentation. (You're not the first or only person, by far, to be tripped up by the naming of dataType.)

That's half the problem. See Stamos' answer for the other half.

Body:
server.js

uses the body parser middleware, handlebars and express

route

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};

client

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).


问:
Processing large xml files
I am having a large xml file which contains many sub elements. I want to able to run some xpath queries. I tried using vtd-xml in java, but I get outofmemory error sometimes, because the xml is so large to fit into memory. Is there an alternative way of processing such large xml's.</p>

答:
What are you trying to do right now?  By the sounds of it you are trying to use a DOM based parser, which essentially loads the entire XML file into memory as a DOM representation.  If you are dealing with a large file, you'll better off using a SAX parser, which processes the XML document in a streaming fashion.

I personally recommend StAX for this.

Title: Processing large xml files


问:
How to get a data set to acutally read as values in order to change them?
Example: Data = (1, 2, 3, 4, 5, 6, 7, 8, 9). I want to subtract the mean value from each value. I tried using

```<code>L= (Data)

G= L - 5.4

print(G)
</code>```

but python doesn't read Data as actual values. How do I get python to read the individual values in my data set and subtract the mean from each one?

Please help. Thank you!

Body:
Example: Data = (1, 2, 3, 4, 5, 6, 7, 8, 9). I want to subtract the mean value from each value. I tried using

L= (Data)

G= L - 5.4

print(G)

but python doesn't read Data as actual values. How do I get python to read the individual values in my data set and subtract the mean from each one?

Please help. Thank you!

Body:
You can use list comprehension:

data = (1, 2, 3, 4, 5, 6, 7, 8, 9)
new_data = tuple(i-sum(data)/float(len(data)) for i in data)

Output:

(-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0)


问:
Python: Change the value of a dictionary key when you come across the key
I'm making a special version of monopoly for a assignment for my school. It's called the Trump mode. The cpu generates random numbers between 2 and 12 as representation of the dice. Every buyable place is bought when you land on it because you have infinite money. It needs to run a few times and calculate the average amount of turns it takes to buy the whole board.

We need to use a dictionary with all the values and places. I'm trying to find a way I can change the value of a key whenever I land on that position, but I can't figure out how.

```<code>beurt = 0
totaal = 0
while totaal < 40:
    worp = throw()
    piece.move(worp)
    print("Na worp {}: {}, {}".format(beurt, board.names[piece.location], board.values[piece.location]))
    totaal = totaal + worp
    beurt += 1
</code>```

This is the code that moves the piece. (The while loop is set to 40 because in my test I want him to stop after one round)

```<code>for key, value in monopoly.monopolyData.dictionary.items() :
    print (key, value)
</code>```

I have this code to print out all my values and keys, but I have no idea how to change the values...

答:
The easiest way for your problem might be to use pop with a default value of 0. This will remove the current field and its value from the dictionary, or return 0 if the field has already been visited. Removing the field as opposed to setting it to 0 has the benefit that you can just use while <your_dict> to loop until each field has been visited.

Simplified example:

```<code>MAX = 20
values = {i: 40 for i in range(MAX)}
position = 0
while values:
    dice = randint(1, 6) + randint(1, 6)
    position = (position + dice) % MAX
    print("pos: {}, val: {}".format(position, values.pop(position, 0)))
</code>```

Body:
I'm making a special version of monopoly for a assignment for my school. It's called the Trump mode. The cpu generates random numbers between 2 and 12 as representation of the dice. Every buyable place is bought when you land on it because you have infinite money. It needs to run a few times and calculate the average amount of turns it takes to buy the whole board.

We need to use a dictionary with all the values and places. I'm trying to find a way I can change the value of a key whenever I land on that position, but I can't figure out how.

beurt = 0
totaal = 0
while totaal < 40:
    worp = throw()
    piece.move(worp)
    print("Na worp {}: {}, {}".format(beurt, board.names[piece.location], board.values[piece.location]))
    totaal = totaal + worp
    beurt += 1

This is the code that moves the piece. (The while loop is set to 40 because in my test I want him to stop after one round)

for key, value in monopoly.monopolyData.dictionary.items() :
    print (key, value)

I have this code to print out all my values and keys, but I have no idea how to change the values...

Body:
The easiest way for your problem might be to use pop with a default value of 0. This will remove the current field and its value from the dictionary, or return 0 if the field has already been visited. Removing the field as opposed to setting it to 0 has the benefit that you can just use while <your_dict> to loop until each field has been visited.

Simplified example:

MAX = 20
values = {i: 40 for i in range(MAX)}
position = 0
while values:
    dice = randint(1, 6) + randint(1, 6)
    position = (position + dice) % MAX
    print("pos: {}, val: {}".format(position, values.pop(position, 0)))


问:
Mysql select rows except first row
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

```<code>SELECT * FROM table ORDER BY id DESC
</code>```

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

```<code>$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");
</code>```

答:
Try this

$other = mysql_query("SELECT * FROM table ORDER BY id DESC OFFSET 1");

THE ABOVE QUERY WONT WORK AS A LIMIT IS NEEDED

Refer to this answer

Title: Mysql select rows except first row

Body:
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

SELECT * FROM table ORDER BY id DESC

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");


问:
Why does my XPath not select based on text()?
I have a page in firefox (no frame) which contains the following part of html code:

```<code>...
<div class="col-sm-6 align-right">
    <a href="/efelg/download_zip" class="alert-link">
        Download all results in .zip format
     </a>
</div>
...
</code>```

which I want to select with a selenium XPATH expression. In order to test my XPATH expression, I installed an add-on for firefox called 'TryXpath' in order to check my expression. However, the expression seems to be incorrect, as no element is selected. Here is the expression:

```<code>//a[text()= "Download all results in .zip format"]
</code>```

but what is wrong with that expression? I found it in different SO answers - but for me this does not seem to work. Why do I get 0 hits? Why is the expression wrong find the html element I posted above (no frame, element is visible and clickable...)

答:
You can try this:

```<code>//a[contains(text(),'Download all results in .zip format')]
</code>```

it is working in my side, Please try at let me know

Body:
I have a page in firefox (no frame) which contains the following part of html code:

...

        Download all results in .zip format

...

which I want to select with a selenium XPATH expression. In order to test my XPATH expression, I installed an add-on for firefox called 'TryXpath' in order to check my expression. However, the expression seems to be incorrect, as no element is selected. Here is the expression:

//a[text()= "Download all results in .zip format"]

but what is wrong with that expression? I found it in different SO answers - but for me this does not seem to work. Why do I get 0 hits? Why is the expression wrong find the html element I posted above (no frame, element is visible and clickable...)

Body:
You can try this:

//a[contains(text(),'Download all results in .zip format')]

it is working in my side, Please try at let me know


Title: How to get a data set to acutally read as values in order to change them?

Body:
>>> Data = (1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> {l - 5.4 for l in Data}
set([1.5999999999999996, -1.4000000000000004, 0.5999999999999996,
3.5999999999999996, 2.5999999999999996, -2.4000000000000004,
-3.4000000000000004, -4.4, -0.40000000000000036])


问:
Difference between completion variables and semaphores
In the linux kernel, semaphores are used to provide mutual exclusion for critical sections of data and Completion variables are used to synchronize between 2 threads waiting on an event. Why not use semaphores for such a synchronization ? Is there any advantage of using a completion variable over a semaphore ?</p>

答:
Explanation of why completions were originally implemented:
http://lkml.indiana.edu/hypermail/linux/kernel/0107.3/0674.html

The basic summary is that we had this
  (fairly common) way of waiting for
  certain events by having a locked
  semaphore on the stack of the waiter,
  and then having the waiter do a
  "down()" which caused it to block
  until the thing it was waiting for did
  an "up()".

This works fairly well, but it has a
  really small (and quite unlikely) race
  on SMP, that is not so much a race of
  the idea itself, as of the
  implementation of the semaphores. We
  could have fixed the semaphores, but
  there were a few reasons not to:

the semaphores are optimized (on purpose) for the non-contention case.
  The "wait for completion" usage has
  the opposite default case

the semaphores are quite involved and architecture-specific, exactly

  due to this optimization. Trying to
  change them is painful as hell.

So instead, I introduced the notion of
  "wait for completion":

More recent thread about completions vs semaphores
http://lkml.org/lkml/2008/4/11/323


问:
ImportError when using tensorflow-gpu
I am new to tensorflow. I have tried to install and use tensorflow-gpu in ubuntu but keep getting the error below, please kindly help me to resolve it.

```<code>ImportError                               Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     57
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59   from tensorflow.python.pywrap_tensorflow_internal import __version__

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py in <module>()
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

~/anaconda3/envs/tensorflow/lib/python3.5/imp.py in load_module(name, file, filename, details)
    242         else:
--> 243             return load_dynamic(name, filename, file)
    244     elif type_ == PKG_DIRECTORY:

~/anaconda3/envs/tensorflow/lib/python3.5/imp.py in load_dynamic(name, path, file)
    342             name=name, loader=loader, origin=path)
--> 343         return _load(spec)
    344

ImportError: /home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/../libtensorflow_framework.so: undefined symbol: cudnnSetRNNDescriptor_v6

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-1-d6579f534729> in <module>()
----> 1 import tensorflow

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/__init__.py in <module>()
     22
     23 # pylint: disable=wildcard-import
---> 24 from tensorflow.python import *
     25 # pylint: enable=wildcard-import
     26

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/__init__.py in <module>()
     47 import numpy as np
     48
---> 49 from tensorflow.python import pywrap_tensorflow
     50
     51 # Protocol buffers

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     70 for some common reasons and solutions.  Include the entire stack trace
     71 above this error message when asking for help.""" % traceback.format_exc()
---> 72   raise ImportError(msg)
     73
     74 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: /home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/../libtensorflow_framework.so: undefined symbol: cudnnSetRNNDescriptor_v6

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
looking at this page you need CuDNN 6.0, the CUDA 8.0 toolkit with associated drivers, a GPU with CUDA Compute Capability 3.0 or higher(you can check that here) and you should install the libcupti-dev library($ sudo apt-get install libcupti-dev).

I hope this helps you a bit further.

Title: ImportError when using tensorflow-gpu

Body:
I am new to tensorflow. I have tried to install and use tensorflow-gpu in ubuntu but keep getting the error below, please kindly help me to resolve it.

ImportError                               Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     57
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59   from tensorflow.python.pywrap_tensorflow_internal import __version__

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py in <module>()
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

~/anaconda3/envs/tensorflow/lib/python3.5/imp.py in load_module(name, file, filename, details)
    242         else:
--> 243             return load_dynamic(name, filename, file)
    244     elif type_ == PKG_DIRECTORY:

~/anaconda3/envs/tensorflow/lib/python3.5/imp.py in load_dynamic(name, path, file)
    342             name=name, loader=loader, origin=path)
--> 343         return _load(spec)
    344

ImportError: /home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/../libtensorflow_framework.so: undefined symbol: cudnnSetRNNDescriptor_v6

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-1-d6579f534729> in <module>()
----> 1 import tensorflow

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/__init__.py in <module>()
     22
     23 # pylint: disable=wildcard-import
---> 24 from tensorflow.python import *
     25 # pylint: enable=wildcard-import
     26

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/__init__.py in <module>()
     47 import numpy as np
     48
---> 49 from tensorflow.python import pywrap_tensorflow
     50
     51 # Protocol buffers

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     70 for some common reasons and solutions.  Include the entire stack trace
     71 above this error message when asking for help.""" % traceback.format_exc()
---> 72   raise ImportError(msg)
     73
     74 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/iai/anaconda3/envs/tensorflow/lib/python3.5/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: /home/iai/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/../libtensorflow_framework.so: undefined symbol: cudnnSetRNNDescriptor_v6

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


问:
C# MVC5 Present string url in view
I am beginning developer in asp.Net MVC5.

In my MVC project i use with web service that return me a string URL the URL is from another domain.

I want to move to the URL.

For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client

```<code>public class HomeController : Controller
{
    public ActionResult Home()
    {
        return View("~/Views/Home/home.cshtml");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult doSomething(Something obj)
    {
        //use web service and get string URL
        string urlString = ;// get from the web service response.
        return View();// want write in the ();
    }
}
</code>```

答:
The url is from another site not the same domain

If you want to redirect to an external URL, you will need to use the Redirect() method.

Like so:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DoSomething(Something obj)
{
    // Use web service to get the string URL
    string urlString = ...;

    if (string.IsNullOrEmpty(urlString))
    {
        // If the urlString is empty, take the user to an Error View.
        return View("Error");
    }

    // Redirect the user to the urlString
    return Redirect(urlString);
}
</code>```

I would recommend also doing some checking to ensure the URL is definitely valid. You can do this using the Uri static method, IsWellFormedUriString() - this returns a bool.

Like so:

```<code>if (!Uri.IsWellFormedUriString(urlString, UrlKind.Absolute))
{
    // If the urlString is not a well-formed Uri, take the user to an Error View
    return View("Error");
}

// Redirect the user to the urlString
return Redirect(urlString);
</code>```

Alternatively, if you're redirecting to an internal Action, use the RedirectToAction() method, as @ankur suggested.

As an extra note: Ensure that your C# method names use PascalCase. Conserve camelCase for local variables/private fields.

So, you would use DoSomething(...), instead of doSomething(...) (I've done this in my example).

Hope this helps.

Title: C# MVC5 Present string url in view

Body:
I am beginning developer in asp.Net MVC5.

In my MVC project i use with web service that return me a string URL the URL is from another domain.

I want to move to the URL.

For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client

public class HomeController : Controller
{
    public ActionResult Home()
    {
        return View("~/Views/Home/home.cshtml");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult doSomething(Something obj)
    {
        //use web service and get string URL
        string urlString = ;// get from the web service response.
        return View();// want write in the ();
    }
}

Body:
The url is from another site not the same domain

If you want to redirect to an external URL, you will need to use the Redirect() method.

Like so:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DoSomething(Something obj)
{
    // Use web service to get the string URL
    string urlString = ...;

    if (string.IsNullOrEmpty(urlString))
    {
        // If the urlString is empty, take the user to an Error View.
        return View("Error");
    }

    // Redirect the user to the urlString
    return Redirect(urlString);
}

I would recommend also doing some checking to ensure the URL is definitely valid. You can do this using the Uri static method, IsWellFormedUriString() - this returns a bool.

Like so:

if (!Uri.IsWellFormedUriString(urlString, UrlKind.Absolute))
{
    // If the urlString is not a well-formed Uri, take the user to an Error View
    return View("Error");
}

// Redirect the user to the urlString
return Redirect(urlString);

Alternatively, if you're redirecting to an internal Action, use the RedirectToAction() method, as @ankur suggested.

As an extra note: Ensure that your C# method names use PascalCase. Conserve camelCase for local variables/private fields.

So, you would use DoSomething(...), instead of doSomething(...) (I've done this in my example).

Hope this helps.


问:
JPA - One to many - duplicate key value error
I need implement join table for users which will have 2 columns USER_CONTACTS(user_id, contact_id)

I need store for contacts lists for users. I need to make possible that user with id 1 can have in contacts user with id 5, but user 5 can also have in contacts user with id 1 (but he musn't).

I need to be possible do following inserts:

```<code>INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(1, 5);
INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(5, 1);
</code>```

Now I got this error:

Unsuccessful: INSERT INTO USERS_CONTACTS(user_id, contact_id)
  VALUES(2, 3) 2017-12-05 15:00:15.146 ERROR 14268 --- [           main]
  org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: duplicate key value
  violates unique constraint "uk_j9ggomsdbjte1eqfo5e61vh8a"

Here is my relationship implementation of User in JPA:

```<code>@Entity
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private long id;

    @OneToMany
    @JoinTable(name = "USERS_CONTACTS",
            joinColumns = @JoinColumn(name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(name = "CONTACT_ID"))
    private List<User> contacts;

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

Can you tell me how to fix it? I am using Postgre 9.5. Thanks.

EDIT

For hibernate I have these properties:

```<code>spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

答: There must not be an unique index on that table! Remove that index and it should work.</p>

Body:
I need implement join table for users which will have 2 columns USER_CONTACTS(user_id, contact_id)

I need store for contacts lists for users. I need to make possible that user with id 1 can have in contacts user with id 5, but user 5 can also have in contacts user with id 1 (but he musn't).

I need to be possible do following inserts:

INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(1, 5);
INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(5, 1);

Now I got this error:

Unsuccessful: INSERT INTO USERS_CONTACTS(user_id, contact_id)
  VALUES(2, 3) 2017-12-05 15:00:15.146 ERROR 14268 --- [           main]
  org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: duplicate key value
  violates unique constraint "uk_j9ggomsdbjte1eqfo5e61vh8a"

Here is my relationship implementation of User in JPA:

@Entity
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private long id;

    @OneToMany
    @JoinTable(name = "USERS_CONTACTS",
            joinColumns = @JoinColumn(name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(name = "CONTACT_ID"))
    private List<User> contacts;

   // ...
}

Can you tell me how to fix it? I am using Postgre 9.5. Thanks.

EDIT

For hibernate I have these properties:

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl


答:
It's an iterable. You can iterate over it with somthing like:</p>

```<code>G = [number - 5.4 for number in Data]
</code>```

Body:
It's an iterable. You can iterate over it with somthing like:

G = [number - 5.4 for number in Data]


问:
OPC-UA server with multiple nodes using eclipse milo
I am building a OPC-UA server using eclipse milo. What are the different ways to provide multiple nodes for a subscription service? Can I define a custom data object having properties of basic data types, for this? How?

I want to have a service which serves data of different data types (Integer, Double, Boolean etc.) as it's output. Each of the values should be named different not single name like array output with single name for all of the values. For this purpose is there a way to define a custom data object class with attributes of different types? Is this possible in OPC to have a custom data object type as output of a service?

答:
Conceptually, adding Nodes with each of the different DataTypes you're asking about is no different than creating a folder node and adding nodes to that.

The ExampleNamespace in the milo-examples project shows you how to do that.

If you truly want to use an instance of a custom ObjectType rather than an instance of FolderType then there's a bit of bookkeeping work you'll need to do.

Create an instance of ObjectTypeNode to describe your new type.

For each property/member it will have, create a new VariableNode with that configured with the DataType you want, then add a HasComponent or HasProperty reference from your ObjectTypeNode to this VariableNode. (These Nodes are what the spec calls InstanceDeclarations)

Add your ObjectTypeNode to the address space as a subtype of BaseObjectTypeNode.

Then, when you created your original ObjectNode, you'd specify the type definition as being your newly created ObjectTypeNode rather than, say, a FolderType.

You can get a better idea about how all this works in Part 3 and 5 of the spec or by using a client like UaExpert to inspect some of the pre-existing ObjectTypes in the server, such as ServerType.

Edit: There's now an example of how to do this here. If this seems a bit bulky... you're right. Typically ObjectTypes and VariableTypes are designed in a modelling tool and imported via a NodeSet XML file, but that's outside the scope of things right now...


问:
Is there a (semantic) difference between the return value of placement new and the casted value of its operand?
Is there a (semantic) difference between the return value of placement new and the casted value of its operand?

```<code>struct Foo { ... };
char buffer[...];

Foo *a = new(buffer) Foo;
Foo *b = reinterpret_cast<Foo *>(buffer);
</code>```

Does a and b differ in some way?

EDIT: Based on DaBler's comment, this question tells that there is a difference, if const/reference members used: Placement new and assignment of class with const member

So, my little-bit updated question: Does a and b differ in any way, if Foo doesn't have const or reference members?

答:
Access through a is legal while b is not. From [basic.compound]

Two objects a and b are pointer-interconvertible if:

they are the same object, or

one is a standard-layout union object and the other is a non-static data member of that object, or

one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, the first base class subobject of that object ([class.mem]), or

there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast. [ Note: An array object and its first element are not pointer-interconvertible, even though they have the same address.  — end note ]

They are not the same object, not unions and not subobjects to each other, therefore not pointer-interconvertible.

Note [expr.reinterpret.cast] only guarantees reinterpret_cast<char*>(b) == buffer.

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_cast<cv T*>(static_cast<cv void*>(v)). [ Note: Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.  — end note ]

Body:
Is there a (semantic) difference between the return value of placement new and the casted value of its operand?

struct Foo { ... };
char buffer[...];

Foo *a = new(buffer) Foo;
Foo *b = reinterpret_cast<Foo *>(buffer);

Does a and b differ in some way?

EDIT: Based on DaBler's comment, this question tells that there is a difference, if const/reference members used: Placement new and assignment of class with const member

So, my little-bit updated question: Does a and b differ in any way, if Foo doesn't have const or reference members?


答:
I assume that uk_j9ggomsdbjte1eqfo5e61vh8a is a leftover from previous  version.

If it were so then just drop the constraint:

```<code>alter table USERS_CONTACTS drop constraint uk_j9ggomsdbjte1eqfo5e61vh8a;
</code>```

Title: JPA - One to many - duplicate key value error

Body:
I assume that uk_j9ggomsdbjte1eqfo5e61vh8a is a leftover from previous  version.

If it were so then just drop the constraint:

alter table USERS_CONTACTS drop constraint uk_j9ggomsdbjte1eqfo5e61vh8a;


问:
How to effectively group non fatal exceptions in Crashlytics (Fabrics)?
We are using Crashlytics in our app as the crash reporting tool.
For Android native crashes, it's working fine and grouping the crashes correctly.
Our app also has few components in react-native. For the crashes which occur in these components, we catch them and then log them to Crashlytics as non-fatal exceptions.

```<code>public class PlatformNativeModuleCallExceptionhandler implements
NativeModuleCallExceptionHandler {
@Override
public void handleException(Exception e) {
    try {
        .
        .
        .
        Crashlytics.logException(new Exception(exceptionString));
    } catch (Exception ex) {}
}
</code>```

Crashes are getting logged in Crashlytics dashboard, but it's showing all the crashes inside a single tab. These might be different crashes of the same or different react-native components.

Due to this we are not able to find out the instances of a particular crash. Need to manually go through each instance of the crash.

I guess it takes the name of the class where exception gets created, in this case PlatformNativeModuleCallExceptionHandler.
I tried creating my own custom exception class but that also did not help.

Does anybody know how we can group the non fatal exceptions better here?
All the similar crashes should be grouped together with their total instances.

答: Crashlytics uses the method and crash line number to group crashes, so if you have an exception handler method for all of your non-fatals, they'll be grouped together. There isn't currently a workaround for this.</p>

Body:
We are using Crashlytics in our app as the crash reporting tool.
For Android native crashes, it's working fine and grouping the crashes correctly.
Our app also has few components in react-native. For the crashes which occur in these components, we catch them and then log them to Crashlytics as non-fatal exceptions.

public class PlatformNativeModuleCallExceptionhandler implements
NativeModuleCallExceptionHandler {
@Override
public void handleException(Exception e) {
    try {
        .
        .
        .
        Crashlytics.logException(new Exception(exceptionString));
    } catch (Exception ex) {}
}

Crashes are getting logged in Crashlytics dashboard, but it's showing all the crashes inside a single tab. These might be different crashes of the same or different react-native components.

Due to this we are not able to find out the instances of a particular crash. Need to manually go through each instance of the crash.

I guess it takes the name of the class where exception gets created, in this case PlatformNativeModuleCallExceptionHandler.
I tried creating my own custom exception class but that also did not help.

Does anybody know how we can group the non fatal exceptions better here?
All the similar crashes should be grouped together with their total instances.


问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答: when you printf("%d", dat[nrow]), dat[nrow] has not been set to 1. In the for loop the condition is i < nrow so it's before it. You need i <= nrow.

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit