问:
Can a query be written in ArangoDB to aggregate values within joined documents?
Let’s say you have a movie subscription service with normal and premium memberships.

Here is a sample of data generated by user activity and stored as documents in a collection:

```<code>[
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 1
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "starwars",
        "sessionGroupID": 1,
        "elapsed": 200
    },
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 2
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 2,
        "elapsed": 500
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 3
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 3,
        "elapsed": 10
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 4
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 4,
        "elapsed": 100
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 5
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 5,
        "elapsed": 5
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "starwars",
        "sessionGroupID": 5,
        "elapsed": 25
    }
]
</code>```

You can see that there are two “eventTypes”:

“sessionInfo” documents that have information common to an entire
user session

“mediaPlay” documents that store how many seconds of a
movie was viewed.

(Each “mediaPlay” event contains the sessionGroupID so it can be associated with that session.)

Question #1:

Given tens of millions of documents total, how would you write a query that totaled the elapsed viewing time of each movie, grouped by userType?

Desired query results:

```<code>premium users - total of "elapsed":
    xmen: 500
    starwars: 200

normal users - total of "elapsed":
    xmen: 115
    starwars: 25
</code>```

Question #2:

If the data is not structured optimally for such a query, what would be the ideal structure?

For example, would it be better to nest the "mediaPlay" events inside each "sessionInfo" docs as a nested array?

Like this?

```<code>[
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 1,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "starwars",
                "sessionGroupID": 1,
                "elapsed": 200
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 2,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 2,
                "elapsed": 500
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 3,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 3,
                "elapsed": 10
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 4,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 4,
                "elapsed": 100
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 5,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 5,
                "elapsed": 5
            },
            {
                "eventType": "mediaPlay",
                "productSKU": "starwars",
                "sessionGroupID": 5,
                "elapsed": 25
            }
        ]
    }
]
</code>```

Thanks for any and all guidance and advice!

答:
The following query iterates over the collection and collect all session IDs grouped by the userTypes. Then it creates a subquery which iterates over the collection and collect all movies and the sum of the elapsed time where eventType is "mediaPlay" and the collected sessions contains the sessionGroupID.

The @@coll is a bind parameter which includes your collection name.

```<code>FOR doc IN @@coll
  FILTER doc.eventType == "sessionInfo"
  COLLECT userTypes = doc.userType INTO sessions = doc.sessionGroupID
  RETURN {
    "userTypes" : userTypes,
    "movies" : (
      FOR event IN @@coll
        FILTER event.sessionGroupID IN sessions
        FILTER event.eventType == "mediaPlay"
        COLLECT movie = event.productSKU INTO elapsed = event.elapsed
        RETURN { "movie" : movie, "elapsed" : SUM(elapsed) }
      )
  }
</code>```

The result of this query is:

```<code>[
  {
    "userTypes": "normal",
    "movies": [
      {
        "movie": "starwars",
        "elapsed": 25
      },
      {
        "movie": "xmen",
        "elapsed": 115
      }
    ]
  },
  {
    "userTypes": "premium",
    "movies": [
      {
        "movie": "starwars",
        "elapsed": 200
      },
      {
        "movie": "xmen",
        "elapsed": 500
      }
    ]
  }
]
</code>```

Regarding your second question. Nested arrays/objects wouldn't optimise this query but you should split your data into two collections. One for every eventType (e.g. name the collections like the eventType sessionInfo and mediaPlay). This reduces the number of needed filter statements and more important, it allows you to query separately over sessionInfos and mediaPlays which highly boost your performance.

The query would then look like:

```<code>FOR doc IN sessionInfo
  COLLECT userTypes = doc.userType INTO sessions = doc.sessionGroupID
  RETURN {
    "userTypes" : userTypes,
    "movies" : (
      FOR event IN mediaPlay
        FILTER event.sessionGroupID IN sessions
        COLLECT movie = event.productSKU INTO elapsed = event.elapsed
        RETURN { "movie" : movie, "elapsed" : SUM(elapsed) }
      )
  }
</code>```

Body:
Let’s say you have a movie subscription service with normal and premium memberships.

Here is a sample of data generated by user activity and stored as documents in a collection:

[
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 1
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "starwars",
        "sessionGroupID": 1,
        "elapsed": 200
    },
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 2
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 2,
        "elapsed": 500
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 3
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 3,
        "elapsed": 10
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 4
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 4,
        "elapsed": 100
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 5
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "xmen",
        "sessionGroupID": 5,
        "elapsed": 5
    },
    {
        "eventType": "mediaPlay",
        "productSKU": "starwars",
        "sessionGroupID": 5,
        "elapsed": 25
    }
]

You can see that there are two “eventTypes”:

“sessionInfo” documents that have information common to an entire
user session

“mediaPlay” documents that store how many seconds of a
movie was viewed.

(Each “mediaPlay” event contains the sessionGroupID so it can be associated with that session.)

Question #1:

Given tens of millions of documents total, how would you write a query that totaled the elapsed viewing time of each movie, grouped by userType?

Desired query results:

premium users - total of "elapsed":
    xmen: 500
    starwars: 200

normal users - total of "elapsed":
    xmen: 115
    starwars: 25

Question #2:

If the data is not structured optimally for such a query, what would be the ideal structure?

For example, would it be better to nest the "mediaPlay" events inside each "sessionInfo" docs as a nested array?

Like this?

[
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 1,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "starwars",
                "sessionGroupID": 1,
                "elapsed": 200
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "premium",
        "sessionGroupID": 2,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 2,
                "elapsed": 500
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 3,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 3,
                "elapsed": 10
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 4,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 4,
                "elapsed": 100
            }
        ]
    },
    {
        "eventType": "sessionInfo",
        "userType": "normal",
        "sessionGroupID": 5,
        "viewLog": [
            {
                "eventType": "mediaPlay",
                "productSKU": "xmen",
                "sessionGroupID": 5,
                "elapsed": 5
            },
            {
                "eventType": "mediaPlay",
                "productSKU": "starwars",
                "sessionGroupID": 5,
                "elapsed": 25
            }
        ]
    }
]

Thanks for any and all guidance and advice!

Body:
The following query iterates over the collection and collect all session IDs grouped by the userTypes. Then it creates a subquery which iterates over the collection and collect all movies and the sum of the elapsed time where eventType is "mediaPlay" and the collected sessions contains the sessionGroupID.

The @@coll is a bind parameter which includes your collection name.

FOR doc IN @@coll
  FILTER doc.eventType == "sessionInfo"
  COLLECT userTypes = doc.userType INTO sessions = doc.sessionGroupID
  RETURN {
    "userTypes" : userTypes,
    "movies" : (
      FOR event IN @@coll
        FILTER event.sessionGroupID IN sessions
        FILTER event.eventType == "mediaPlay"
        COLLECT movie = event.productSKU INTO elapsed = event.elapsed
        RETURN { "movie" : movie, "elapsed" : SUM(elapsed) }
      )
  }

The result of this query is:

[
  {
    "userTypes": "normal",
    "movies": [
      {
        "movie": "starwars",
        "elapsed": 25
      },
      {
        "movie": "xmen",
        "elapsed": 115
      }
    ]
  },
  {
    "userTypes": "premium",
    "movies": [
      {
        "movie": "starwars",
        "elapsed": 200
      },
      {
        "movie": "xmen",
        "elapsed": 500
      }
    ]
  }
]

Regarding your second question. Nested arrays/objects wouldn't optimise this query but you should split your data into two collections. One for every eventType (e.g. name the collections like the eventType sessionInfo and mediaPlay). This reduces the number of needed filter statements and more important, it allows you to query separately over sessionInfos and mediaPlays which highly boost your performance.

The query would then look like:

FOR doc IN sessionInfo
  COLLECT userTypes = doc.userType INTO sessions = doc.sessionGroupID
  RETURN {
    "userTypes" : userTypes,
    "movies" : (
      FOR event IN mediaPlay
        FILTER event.sessionGroupID IN sessions
        COLLECT movie = event.productSKU INTO elapsed = event.elapsed
        RETURN { "movie" : movie, "elapsed" : SUM(elapsed) }
      )
  }


来源: stackexchange

问:
Quicksort with insertion Sort finish - where am I going wrong?
I am working on a project for a class. We are to write a quick-sort that transitions to a insertion sort at the specified value. Thats no problem, where I am now having difficulty is figuring out why I am not getting the performance I expect.

One of the requirements is that it must sort an array of 5,00,000 ints in under 1,300 ms (this is on standard machines, so CPU speed is not an issue). First of all, I can't get it to work on 5,000,000 because of a stack overflow error (too many recursive calls...). If I increase the heap size, I am still getting a lot slower than that.

Below is the code. Any hints anyone?

Thanks in advance

```<code>public class MyQuickSort {

    public static void sort(int [] toSort, int moveToInsertion)
    {
        sort(toSort, 0, toSort.length - 1, moveToInsertion);
    }

    private static void sort(int[] toSort, int first, int last, int moveToInsertion)
    {
        if (first < last)
        {
            if ((last - first) < moveToInsertion)
            {
                insertionSort(toSort, first, last);
            }
            else
            {
                int split = quickHelper(toSort, first, last);
                sort(toSort, first, split - 1, moveToInsertion);
                sort(toSort, split + 1, last, moveToInsertion);
            }
        }
    }

    private static int quickHelper(int[] toSort, int first, int last)
    {
        sortPivot(toSort, first, last);
        swap(toSort, first, first + (last - first)/2);
        int left = first;
        int right = last;
        int pivotVal = toSort[first];
        do
        {
            while ( (left < last) && (toSort[left] <= pivotVal))
            {
                left++;
            }

            while (toSort[right] > pivotVal)
            {
                right--;
            }

            if (left < right)
            {
                swap(toSort, left, right);
            }

        } while (left < right);

        swap(toSort, first, right);

        return right;
    }

    private static void sortPivot(int[] toSort, int first, int last)
    {
        int middle = first + (last - first)/2;

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

        if (toSort[last] < toSort[middle]) swap(toSort, middle, last);

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

    }

    private static void insertionSort(int [] toSort, int first, int last)
    {
         for (int nextVal = first + 1; nextVal <= last; nextVal++)
            {
                int toInsert = toSort[nextVal];
                int j = nextVal - 1;
                while (j >= 0 && toInsert < toSort[j])
                {
                    toSort[j + 1] = toSort[j];
                    j--;
                }
                toSort[j + 1] = toInsert;
            }
    }

    private static void swap(int[] toSort, int i, int j)
    {
        int temp = toSort[i];
        toSort[i] = toSort[j];
        toSort[j] = temp;
    }

}
</code>```

答:
When the input array is large, its natural to expect that recursive functions run into stack overflow issues. which is what is happening here when you try with the above code. I would recommend you to write iterative Quicksort using your own stack. It should be fast because there is no stack frame allocations/deallocations done at run time. You won't run into stack overflow issues also. Performance also depends on at what point you are running insertion sort. I don't have a particular input size where insertion sort performs badly compared to quicksort. I would suggest you to try with different sizes and I'm sure you will notice difference.

You might also want to use binary search in insertion sort to improve performance. I don't know how much it improves when you run on smaller input but its a nice trick to play.

I don't want to share code because that doesn't make you learn how to convert recursive quicksort to iterative one. If you have problems in converting to iterative one let me know.

ContentLicense: CC BY-SA 2.5

Body:
I am working on a project for a class. We are to write a quick-sort that transitions to a insertion sort at the specified value. Thats no problem, where I am now having difficulty is figuring out why I am not getting the performance I expect.

One of the requirements is that it must sort an array of 5,00,000 ints in under 1,300 ms (this is on standard machines, so CPU speed is not an issue). First of all, I can't get it to work on 5,000,000 because of a stack overflow error (too many recursive calls...). If I increase the heap size, I am still getting a lot slower than that.

Below is the code. Any hints anyone?

Thanks in advance

public class MyQuickSort {

    public static void sort(int [] toSort, int moveToInsertion)
    {
        sort(toSort, 0, toSort.length - 1, moveToInsertion);
    }

    private static void sort(int[] toSort, int first, int last, int moveToInsertion)
    {
        if (first < last)
        {
            if ((last - first) < moveToInsertion)
            {
                insertionSort(toSort, first, last);
            }
            else
            {
                int split = quickHelper(toSort, first, last);
                sort(toSort, first, split - 1, moveToInsertion);
                sort(toSort, split + 1, last, moveToInsertion);
            }
        }
    }

    private static int quickHelper(int[] toSort, int first, int last)
    {
        sortPivot(toSort, first, last);
        swap(toSort, first, first + (last - first)/2);
        int left = first;
        int right = last;
        int pivotVal = toSort[first];
        do
        {
            while ( (left < last) && (toSort[left] <= pivotVal))
            {
                left++;
            }

            while (toSort[right] > pivotVal)
            {
                right--;
            }

            if (left < right)
            {
                swap(toSort, left, right);
            }

        } while (left < right);

        swap(toSort, first, right);

        return right;
    }

    private static void sortPivot(int[] toSort, int first, int last)
    {
        int middle = first + (last - first)/2;

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

        if (toSort[last] < toSort[middle]) swap(toSort, middle, last);

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

    }

    private static void insertionSort(int [] toSort, int first, int last)
    {
         for (int nextVal = first + 1; nextVal <= last; nextVal++)
            {
                int toInsert = toSort[nextVal];
                int j = nextVal - 1;
                while (j >= 0 && toInsert < toSort[j])
                {
                    toSort[j + 1] = toSort[j];
                    j--;
                }
                toSort[j + 1] = toInsert;
            }
    }

    private static void swap(int[] toSort, int i, int j)
    {
        int temp = toSort[i];
        toSort[i] = toSort[j];
        toSort[j] = temp;
    }

}


问:
Horizontal aligment WPF expander header
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

```<code><Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>
        <Style TargetType="{x:Type Expander}">
            <Setter Property="Background" Value="#f0f0f5"></Setter>
            <Setter Property="TextElement.FontFamily" Value="Arial Nova"/>
        </Style>
    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>
</code>```

My ButtonStyle :

```<code><Style x:Key="ButtonStyle" TargetType="Button">

            <Setter Property="Background" Value="#66e0ff" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontSize" Value="15" />
            <Setter Property="SnapsToDevicePixels" Value="True" />

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border CornerRadius="4" Background="{TemplateBinding Background}">
                            <Grid>
                                <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="White" />
                                <Setter Property="Foreground" Value="#66e0ff" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

    </Style>
</code>```

I tried also with an DockPanel, but same result.

答:
You need to set the HorizontalAlignment property of the ContentPresenter that is defined in the Expander's default control template to Stretch.

The easiest way to do this is probably to handle the Loaded event of the Expander and use a helper method that finds the ContentPresenter in the visual tree:

```<code>private void Expander_Loaded(object sender, RoutedEventArgs e)
{
    Expander expander = sender as Expander;
    System.Windows.Controls.Primitives.ToggleButton HeaderSite = GetChildOfType<System.Windows.Controls.Primitives.ToggleButton>(expander);
    if (HeaderSite != null)
    {
        ContentPresenter cp = GetChildOfType<ContentPresenter>(HeaderSite);
        if (cp != null)
            cp.HorizontalAlignment = HorizontalAlignment.Stretch;
    }
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null) return result;
    }
    return null;
}
</code>```

```<code><Expander IsExpanded="True" Loaded="Expander_Loaded">
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" DockPanel.Dock="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>
        <Style TargetType="{x:Type Expander}">
            <Setter Property="Background" Value="#f0f0f5"></Setter>
            <Setter Property="TextElement.FontFamily" Value="Arial Nova"/>
        </Style>
    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Horizontal aligment WPF expander header

Body:
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

<Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>

    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>

My ButtonStyle :

I tried also with an DockPanel, but same result.

Body:
You need to set the HorizontalAlignment property of the ContentPresenter that is defined in the Expander's default control template to Stretch.

The easiest way to do this is probably to handle the Loaded event of the Expander and use a helper method that finds the ContentPresenter in the visual tree:

private void Expander_Loaded(object sender, RoutedEventArgs e)
{
    Expander expander = sender as Expander;
    System.Windows.Controls.Primitives.ToggleButton HeaderSite = GetChildOfType<System.Windows.Controls.Primitives.ToggleButton>(expander);
    if (HeaderSite != null)
    {
        ContentPresenter cp = GetChildOfType<ContentPresenter>(HeaderSite);
        if (cp != null)
            cp.HorizontalAlignment = HorizontalAlignment.Stretch;
    }
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null) return result;
    }
    return null;
}

<Expander IsExpanded="True" Loaded="Expander_Loaded">
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" DockPanel.Dock="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>
        <Style TargetType="{x:Type Expander}">
            <Setter Property="Background" Value="#f0f0f5"></Setter>
            <Setter Property="TextElement.FontFamily" Value="Arial Nova"/>
        </Style>
    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>


问:
Direct Mapped Cache, Filling out Contents of Main Memory
I am preparing for an exam in Computer Architecture. I understand how caching works and how data gets copied from Main Memory to the Cache depending on the Address.

However, I am unable to figure out how the contents of a main memory are filled out depending on the address. For instance, in the image linked to below, I can easily fill out the contents of the cache, but I do not understand how I should fill the cells that are pointed at with the arrows.

My Professor did not really talk much about that part and I can't complete the actual problem without further help. Please help me understand how I should fill the contents of the Main Memory!

答:
There are few ways you can fill out the main memory.

When a cache entry is evicted from, it is stored in the main memory.

When your program load data to memory, from a file. Lets say you have an image you want to process, you can load this to memory and process it than accessing the data from file every time, which is slower.

Direct Memory Access (DMA) operations - These are there to read/write memory without CPU interaction. You may have a DMA operation filling out an input buffer which then CPU processes.

You could have multiple programs working together, one producing data and other consuming it. For example, your first program may be doing a matrix multiplication and the second is using that result. So the first program will write out its result to main memory and will pass a reference to the second program to use it.


问:
CoreData disappearance of relationship after saving problem
I have a to-many relationship in my CoreData model without an inverse relationship which causes some strange behaviours.

For example: Entity of type A has a to-many relationship to an entity of type B. There is no inverse relationship from B to A. Now when I connect objects of type A with some objects of type B there is no problem. But after saving the whole management object context and restarting the application, the connections between the objects are no longer there except for one object (which has still the relationship). It can happen that different objects of type A has a relationship to one specific entity of type B - so they are sharing the same object.

What could be the problem?

答:
The simplest explanation is that you don't actually have a to-many relationship set but rather a to-one. You just save the last B you set. I would log the relationship immediately before saving to confirm whether only one B is set.

Alternatively, without a reciprocal relationship, it is possible for an object to disappear from the graph without producing an error. If B has no relationship to A that means that B is not observing A and doesn't care what happens to it. You may be altering the graph without being aware. Delete rules can also cause odd behavior in this circumstance.

You should only use relationships without inverses in very rare cases. The inverse relationships help maintain the integrity of the object graph and prevents orphaned or disappearing objects.


问:
Execute SQL script from C# and logging errors
I am trying to execute a script (.sql file) on a database from a C# Windows application. The SQL file contains 'GO' statements; this means I am using the object SMO.

I am trying to continue on error and also log any error which might occur during the execution of the script on the database. Is there any way to do this?

This is the code I'm using:

```<code>using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    ServerConnection svrConnection = new ServerConnection(sqlConnection);
    Server server = new Server(svrConnection);

    string script = File.ReadAllText("upgradeDatabase.sql");

    try
    {
        server.ConnectionContext.ExecuteNonQuery(script, ExecutionTypes.ContinueOnError);
     }
     catch (Exception ex)
     {
         //handling and logging for the errors are done here
     }
}
</code>```

Any help is appreciated!

答:
I'm not programmer (DBA), therefore I'm not sure.
I assume following can be helpful

svrConnection.FireInfoMessageEventOnUserErrors = true;

Body:
I am trying to execute a script (.sql file) on a database from a C# Windows application. The SQL file contains 'GO' statements; this means I am using the object SMO.

I am trying to continue on error and also log any error which might occur during the execution of the script on the database. Is there any way to do this?

This is the code I'm using:

using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    ServerConnection svrConnection = new ServerConnection(sqlConnection);
    Server server = new Server(svrConnection);

    string script = File.ReadAllText("upgradeDatabase.sql");

    try
    {
        server.ConnectionContext.ExecuteNonQuery(script, ExecutionTypes.ContinueOnError);
     }
     catch (Exception ex)
     {
         //handling and logging for the errors are done here
     }
}

Any help is appreciated!


问:
Cannot get AppInsights working under Spring Boot
I followed the https://learn.microsoft.com/en-us/azure/application-insights/app-insights-java-get-started, but still without success.

I have applicationinsights-web dependency in place via maven

I added ApplicationInsights.xml to main/resources with hardcoded instrumentation key and even with <SDKLogger /> inside

I added the scan path: @ComponentScan({...., "com.microsoft.applicationinsights.web.spring"})

Results:

I see no logs about looking up the configuration file, even if I make the syntax error in in or remove it completely

in debug I see that RequestNameHandlerInterceptorAdapter is instantiated via com.microsoft.applicationinsights.web.spring.internal.InterceptorRegistry, and during calls the preHandle method is called, but calls to ThreadContext.getRequestTelemetryContext() returns always null and nothing more happens

It looks like it is something obvious, but no idea what. What part/classes are responsible for loading the configuration file?

答:
I was a little bit confused with documentation. As mentioned by yonisha, the filter does the whole magic. The following configuration class takes care of creating and adding the filter in Spring Boot application.

```<code>import com.microsoft.applicationinsights.web.internal.WebRequestTrackingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

@Configuration
@ComponentScan("com.microsoft.applicationinsights.web.spring")
public class ApplicationInsightsConfiguration {

@Bean
public FilterRegistrationBean someFilterRegistration() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(appInsightsWebRequestTrackingFilter());
    registration.addUrlPatterns("/*");
    registration.setName("webRequestTrackingFilter");
    registration.setOrder(1);
    return registration;
}

@Bean(name = "appInsightsWebRequestTrackingFilter")
public Filter appInsightsWebRequestTrackingFilter() {
    return new WebRequestTrackingFilter();
}
</code>```

Important: It will work nicely if you set the server.context-path property to some value. If not, AI initialization will fail with error

```<code>AI: ERROR 03-04-2017 14:11, 20: WebApp name is not found, unable to register WebApp
</code>```

In order to keep servlet-context empty, I had to implement wrappers for the filter and 2 other classes to override it, but it was a very dirty fix... Would be great, if the name could be passed as a parameter to the filter, but that is not yet possible (https://github.com/Microsoft/ApplicationInsights-Java/issues/359)

Body:
I was a little bit confused with documentation. As mentioned by yonisha, the filter does the whole magic. The following configuration class takes care of creating and adding the filter in Spring Boot application.

import com.microsoft.applicationinsights.web.internal.WebRequestTrackingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

@Configuration
@ComponentScan("com.microsoft.applicationinsights.web.spring")
public class ApplicationInsightsConfiguration {

@Bean
public FilterRegistrationBean someFilterRegistration() {

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(appInsightsWebRequestTrackingFilter());
    registration.addUrlPatterns("/*");
    registration.setName("webRequestTrackingFilter");
    registration.setOrder(1);
    return registration;
}

@Bean(name = "appInsightsWebRequestTrackingFilter")
public Filter appInsightsWebRequestTrackingFilter() {
    return new WebRequestTrackingFilter();
}

Important: It will work nicely if you set the server.context-path property to some value. If not, AI initialization will fail with error

AI: ERROR 03-04-2017 14:11, 20: WebApp name is not found, unable to register WebApp

In order to keep servlet-context empty, I had to implement wrappers for the filter and 2 other classes to override it, but it was a very dirty fix... Would be great, if the name could be passed as a parameter to the filter, but that is not yet possible (https://github.com/Microsoft/ApplicationInsights-Java/issues/359)


问:
Linq query to get person visited zones of current day
I am working on web api with Entity framework as object-relational mapping (ORM) framework for ADO.NET. I need to write a linq query which should return most recent 5 zones traveled by a person.

My table with respective columns is depicted in the attached image. I am using azure sql database as my back-end storage, from the above data i need to get top 5 zone_id list as [4,2,3,2,1] by using linq query. client may request to get zones list with in specific range of stime.

答:
Your question is unclear about what the expected result is. You state that you want the 5 most recent zones the person traveled in, which, according to your picture should result in [4,2,3,3,2] however you state the result should be [4,2,3,2,1] which is not in chronological order.

Nevertheless, the LINQ statement you would use to filter the data by the record's 5 most recently traveled zones would be:

```<code>int[] mostRecentZones = _ctx.OrderByDescending(x=>x.stime).Take(5).Select(x=>x.zone_id).ToArray();
</code>```

Assuming '_ctx' is the name of you DBContext object and 'stime' is a DateTime object and 'zone_id' is an integer field.

Body:
Your question is unclear about what the expected result is. You state that you want the 5 most recent zones the person traveled in, which, according to your picture should result in [4,2,3,3,2] however you state the result should be [4,2,3,2,1] which is not in chronological order.

Nevertheless, the LINQ statement you would use to filter the data by the record's 5 most recently traveled zones would be:

int[] mostRecentZones = _ctx.OrderByDescending(x=>x.stime).Take(5).Select(x=>x.zone_id).ToArray();

Assuming '_ctx' is the name of you DBContext object and 'stime' is a DateTime object and 'zone_id' is an integer field.


问:
Split big FO to smaller PDFs

I have a big table (black borders on picture) lets say 2.5 x A4 Format.
Is it possible to split/divide/crop big table to smaller segments (red borders on picture) to get PDF file contains A4 formatted pages?

答:
Yes, you can do this.

Create 3 page sequences

render the table in each page sequence, in a block-container wide enough for the whole table (i.e. on the first page, the table will run off the right side of the page)

in the first sequence, render the table normally

in the second and third sequence, give the table an offset:

<fo:block-container left="-297mm"> (or 2x 297 mm for the third page sequence)

Title: Split big FO to smaller PDFs


问:
Circumvent the sed backreference limit \1 through \9
The sed manual clearly states that the available backreferences available for the replacement string in a substitute are numbered \1 through \9. I'm trying to parse a log file that has 10 fields.

I have the regex formed for it but the tenth match (and anything after) isn't accessible.

Does anyone have an elegant way to circumvent this limitation in KSH (or any language that perhaps I can port to shell scripting)?

答:
You're asking for a shell script solution - that means you're not limited to using just sed, correct?  Most shells support arrays, so perhaps you can parse the line into a shell array variable?  If need be, you could even parse the same line multiple times, extracting different bits of information on each pass.

Would that do?


问:
please explain me. 'Plugin with id not found', 'Android NDK undefined modules'
I downloaded 'Tess-two' library.
After project was ndk-builded&ant release in cmd, I import library in my project.

here was one error.

```<code>'Plugin with id 'com.github.dcendents.android-maven' not found.'
</code>```

I had solved, just add 2 line in my app module gradle.
-like this

```<code>classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
</code>```

The error was completely solved, however another error appeared.

```<code>C:/android-ndk-r14/build//../build/core/build-binary.mk:687: Android NDK: Module
 pngt depends on undefined modules: z
C:/android-ndk-r14/build//../build/core/build-binary.mk:700: *** Android NDK: Ab
orting (set APP_ALLOW_MISSING_DEPS=true to allow missing dependencies).Stop.
</code>```

At this time, I just added one line in tess-two\jni\Application.mk.

```<code>APP_ALLOW_MISSING_DEPS=true
</code>```

Now, my project can build very well.
But I can't understand what I did.

Somebody please explain to me. What mean that error and how that codes could solve that error.

答:
File > Project Structure

As I wrote above, since it is the specification of NDK r14, we could do it after downloading NDK r13b.

It will be r14 in the near future, but you can also download old revisions, so please check them yourself.

Body:
I downloaded 'Tess-two' library.
After project was ndk-builded&ant release in cmd, I import library in my project.

here was one error.

'Plugin with id 'com.github.dcendents.android-maven' not found.'

I had solved, just add 2 line in my app module gradle.
-like this

classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'

The error was completely solved, however another error appeared.

C:/android-ndk-r14/build//../build/core/build-binary.mk:687: Android NDK: Module
 pngt depends on undefined modules: z
C:/android-ndk-r14/build//../build/core/build-binary.mk:700: *** Android NDK: Ab
orting (set APP_ALLOW_MISSING_DEPS=true to allow missing dependencies).Stop.

At this time, I just added one line in tess-two\jni\Application.mk.

APP_ALLOW_MISSING_DEPS=true

Now, my project can build very well.
But I can't understand what I did.

Somebody please explain to me. What mean that error and how that codes could solve that error.


问:
Microseconds to human readable output
I have a need to convert microseconds to a human readable format. While I would be able convert it to HH:MM:SS.MS, I'm not sure the best way to strip the 00:'s if present I would like work with these

```<code>input = [ 12040000, 60042000, 15582000000 ]
output = [ '12.04', '1:00.42', '4:19:27' ]

function formatMark(mu) {
    var timeList = []
    var ms = mu / 1000
    var time = new Date(ms)

    var ms = time.getMilliseconds()
    var ss = time.getSeconds()
    var mm = time.getMinutes()
    var hh = time.getHours()

    if (ms > 1) timeList.push(ms) //
    if (ss > 1) timeList.push(ss) //
    if (mm > 1) timeList.push(mm) //
    if (hh > 1) timeList.push(hh) //

    return { hh + ':' + mm + ':' + ss + '.' + ms }

 }
</code>```

Unfortunately the code above doesn't work, probably for multiple reasons in which I'd be better off knowing, but I really just need a conventional and readable output. Any tips / suggestions are appreciated!

答:
As per your question, you are passing parameter as array type but the function is not compatible to handle this, your logic for calculating readable time string is correct. only thing is that you need to handle this for array type parameter.

```<code>function formatMark(mu) {
     var timeList = []
     mu.map(function(t){
           var ms = mu / 1000
           var time = new Date(ms)
           var ms = time.getMilliseconds()
           var ss = time.getSeconds()
           var mm = time.getMinutes()
           var hh = time.getHours()

           if (ms > 1) timeList.push(ms) //
           if (ss > 1) timeList.push(ss) //
           if (mm > 1) timeList.push(mm) //
           if (hh > 1) timeList.push(hh) //
           var timeString=hh + ':' + mm + ':' + ss + '.' + ms
           console.log(timeString)
           timeList.push(timeString)
      })
      return timeList;
}
</code>```

This function accepts array and returns the array of readable time strings.

Title: Microseconds to human readable output

Body:
I have a need to convert microseconds to a human readable format. While I would be able convert it to HH:MM:SS.MS, I'm not sure the best way to strip the 00:'s if present I would like work with these

input = [ 12040000, 60042000, 15582000000 ]
output = [ '12.04', '1:00.42', '4:19:27' ]

function formatMark(mu) {
    var timeList = []
    var ms = mu / 1000
    var time = new Date(ms)

    var ms = time.getMilliseconds()
    var ss = time.getSeconds()
    var mm = time.getMinutes()
    var hh = time.getHours()

    if (ms > 1) timeList.push(ms) //
    if (ss > 1) timeList.push(ss) //
    if (mm > 1) timeList.push(mm) //
    if (hh > 1) timeList.push(hh) //

    return { hh + ':' + mm + ':' + ss + '.' + ms }

 }

Unfortunately the code above doesn't work, probably for multiple reasons in which I'd be better off knowing, but I really just need a conventional and readable output. Any tips / suggestions are appreciated!

Body:
As per your question, you are passing parameter as array type but the function is not compatible to handle this, your logic for calculating readable time string is correct. only thing is that you need to handle this for array type parameter.

function formatMark(mu) {
     var timeList = []
     mu.map(function(t){
           var ms = mu / 1000
           var time = new Date(ms)
           var ms = time.getMilliseconds()
           var ss = time.getSeconds()
           var mm = time.getMinutes()
           var hh = time.getHours()

           if (ms > 1) timeList.push(ms) //
           if (ss > 1) timeList.push(ss) //
           if (mm > 1) timeList.push(mm) //
           if (hh > 1) timeList.push(hh) //
           var timeString=hh + ':' + mm + ':' + ss + '.' + ms
           console.log(timeString)
           timeList.push(timeString)
      })
      return timeList;
}

This function accepts array and returns the array of readable time strings.


答:
Can you user perl -pe 's/(match)(str)/$2$1/g;' in place of sed?  The way to circumvent the backreference limit is to use something other than sed.

Also, I suppose you could do your substitution in two steps, but I don't know your pattern so I can't help you out with how.

Title: Circumvent the sed backreference limit \1 through \9

Body:
The sed manual clearly states that the available backreferences available for the replacement string in a substitute are numbered \1 through \9. I'm trying to parse a log file that has 10 fields.

I have the regex formed for it but the tenth match (and anything after) isn't accessible.

Does anyone have an elegant way to circumvent this limitation in KSH (or any language that perhaps I can port to shell scripting)?


问:
Auto Login using Python to my local internet page
I have cable internet which requires me to login though a web page. It's annoying how it resets every day at 8 and 12am. I wanted to write a python script which will automate the login process. I've read many StackOverflow solutions so far, nothing has worked. I have tried Requests, Twill, RoboBrowser etc.

Upon inspecting the page source I came across a doLogin() ajax script, which is triggered by login button. Here is the full page source.

following is one of my implementations which fails

```<code>import requests

# Fill in your details here to be posted to the login form.
payload = {
    'action': 'http://10.10.0.1/login',
    'actualusername': 'username',
    'actualpassword': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post("http://103.251.83.134/captiveportal/Default.aspx", data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    #r = s.get('http://www.google.com')
    #print r.text
</code>```

EDIT: Solution

I used Selenium WebDriver to fix this. Check answer.

答:
Use Selenium :) Download ChromeDriver to the path, make a two-time variable and check the time every minute. If it's 'login time', your browser will pass through the authorization.</p>

```<code>from selenium import webdriver

def Authorization_for_broadband():
    driver = webdriver.Chrome("C:\YOURPATHTO\CHROMEDRIVER.EXE")

    driver.get('http://10.10.0.1/login')
    driver.find_element_by_xpath('//*[@id="username"]').send_keys('USERNAME')
    driver.find_element_by_xpath('//*[@id="password"]').send_keys('PASSWORD')
    driver.find_element_by_xpath('//*[@id="btnLogin"]').click()
    driver.close

while(1):
    if time=='your-login-period1' or time == 'your-login-period2':
        Authorization_for_broadband()
</code>```

Body:
I have cable internet which requires me to login though a web page. It's annoying how it resets every day at 8 and 12am. I wanted to write a python script which will automate the login process. I've read many StackOverflow solutions so far, nothing has worked. I have tried Requests, Twill, RoboBrowser etc.

Upon inspecting the page source I came across a doLogin() ajax script, which is triggered by login button. Here is the full page source.

following is one of my implementations which fails

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'action': 'http://10.10.0.1/login',
    'actualusername': 'username',
    'actualpassword': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post("http://103.251.83.134/captiveportal/Default.aspx", data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    #r = s.get('http://www.google.com')
    #print r.text

EDIT: Solution

I used Selenium WebDriver to fix this. Check answer.

Body:
Use Selenium :) Download ChromeDriver to the path, make a two-time variable and check the time every minute. If it's 'login time', your browser will pass through the authorization.

from selenium import webdriver

def Authorization_for_broadband():
    driver = webdriver.Chrome("C:\YOURPATHTO\CHROMEDRIVER.EXE")

    driver.get('http://10.10.0.1/login')
    driver.find_element_by_xpath('//*[@id="username"]').send_keys('USERNAME')
    driver.find_element_by_xpath('//*[@id="password"]').send_keys('PASSWORD')
    driver.find_element_by_xpath('//*[@id="btnLogin"]').click()
    driver.close

while(1):
    if time=='your-login-period1' or time == 'your-login-period2':
        Authorization_for_broadband()

ContentLicense: CC BY-SA 4.0


问:
UWP data persistence after uninstall the app
In my UWP application now I store some value in the ApplicationData.Current.LocalSettings and when I uninstall the app all the values will be lost. I need to know do we have any place to store the value which will be save and can be accessed even after I reinstall the app in the device?

I need similar like what we do it in Windows application (WPF) read/write with system registry and I understand that we can do it UWP applications.

答: You are looking for the ApplicationData.Current.RoamingFolder which allows you to save and sync settings between all installations of the same user


问:
HTTP URL Address Encoding in Java
My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly...

Example:

```<code>URL:  http://search.barnesandnoble.com/booksearch/first book.pdf

java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");
</code>```

returns me:

```<code>http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf
</code>```

But, what I want is

```<code>http://search.barnesandnoble.com/booksearch/first%20book.pdf
</code>```

(space replaced by %20)

I guess URLEncoder is not designed to encode HTTP URLs... The JavaDoc says "Utility class for HTML form encoding"... Is there any other way to do this?

答:
I had the same problem. Solved this by unsing:

```<code>android.net.Uri.encode(urlString, ":/");
</code>```

It encodes the string but skips ":" and "/".

Title: HTTP URL Address Encoding in Java

Body:
My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly...

Example:

URL:  http://search.barnesandnoble.com/booksearch/first book.pdf

java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");

returns me:

http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf

But, what I want is

http://search.barnesandnoble.com/booksearch/first%20book.pdf

(space replaced by %20)

I guess URLEncoder is not designed to encode HTTP URLs... The JavaDoc says "Utility class for HTML form encoding"... Is there any other way to do this?

Body:
I had the same problem. Solved this by unsing:

android.net.Uri.encode(urlString, ":/");

It encodes the string but skips ":" and "/".


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
From Smalltalk you can learn real object-oriented programming. Hybrids like java, c# and Delphi don't seem to do so well. After ten years of hybrids, my coding style significantly improved after a few months of Smalltalk.

As an iPhone developer, you're probably more interested in the design of the libraries and the concepts used than the syntax. c is not going to be any help there (though you need to understand some basics). Programming in Objective C feels much more similar to programming in Smalltalk. The Smalltalk IDEs are far superior to the Objective C ones, and help you understand much better how object-oriented code works, and how to build it. It is much easier to keep your code clean and well-refactored in a Smalltalk (IDE) than in any other object-oriented language. The cocoa libraries are very well designed, at least when compared to the java or .net ones. They seem to be in somewhat better shape than e.g. the Squeak Smalltalk ones.


问:
How do I eliminate all the parenthesis in a txt files?
I have a txt file, single COLUMN, taken from excel, of the following type:

AMANDA (LOUDLY SPEAKING)
JEFF
STEVEN (TEASINGLY)
AMANDA
DOC BRIAN GREEN

As output I want:

AMANDA
JEFF
STEVEN
AMANDA
DOC BRIAN GREEN

I tried with a for cycle on all the column and then:

```<code>            if (str[i] == '('):
                return str.split('(')
</code>```

but it's clearly not working.
Do you have any possible solution? I would then need an output file as my original txt, so with each name for each line in a single column.

Thanks everyone!
(I am using PyCharm 3.2)

答:
I'd use regex in this situation. \w will replace letters, the * will select 0 or more.  Then we check that it is between parenthesis.

```<code>import re
fi = "AMANDA (LOUDLY) JEFF STEVEN (TEASINGLY) AMANDA"
with open("mytext.txt","r") as fi, open("out.txt", "w") as fo:
    for line in fi:
        fo.write(re.sub("\(.*?\)", "", line))
</code>```

Body:
I have a txt file, single COLUMN, taken from excel, of the following type:

AMANDA (LOUDLY SPEAKING)
JEFF
STEVEN (TEASINGLY)
AMANDA
DOC BRIAN GREEN

As output I want:

AMANDA
JEFF
STEVEN
AMANDA
DOC BRIAN GREEN

I tried with a for cycle on all the column and then:

            if (str[i] == '('):
                return str.split('(')

but it's clearly not working.
Do you have any possible solution? I would then need an output file as my original txt, so with each name for each line in a single column.

Thanks everyone!
(I am using PyCharm 3.2)

Body:
I'd use regex in this situation. \w will replace letters, the * will select 0 or more.  Then we check that it is between parenthesis.

import re
fi = "AMANDA (LOUDLY) JEFF STEVEN (TEASINGLY) AMANDA"
with open("mytext.txt","r") as fi, open("out.txt", "w") as fo:
    for line in fi:
        fo.write(re.sub("\(.*?\)", "", line))


问:
Sorting rows in DataTable by extracting a number
I have a question that could maybe be simple. I have some values in a datatable column like "F-213", "F-1113/A" and so on. Is it possible to extract the number of these and sort the rows of the table by the number? I tried something like this:

```<code>DataTable orderedDt = _table.AsEnumerable()
            .OrderBy(r => int.Parse(r.Field<string>(int.Parse(Regex.Match("F-Number", @"\d+").Value))))
            .CopyToDataTable();
</code>```

but I'm getting an Format exception.

Thank you!

答:
Please see:
https://msdn.microsoft.com/en-us/library/0z2heewz(v=vs.110).aspx

Is the input always?

F-Number

Body:
I have a question that could maybe be simple. I have some values in a datatable column like "F-213", "F-1113/A" and so on. Is it possible to extract the number of these and sort the rows of the table by the number? I tried something like this:

DataTable orderedDt = _table.AsEnumerable()
            .OrderBy(r => int.Parse(r.Field<string>(int.Parse(Regex.Match("F-Number", @"\d+").Value))))
            .CopyToDataTable();

but I'm getting an Format exception.

Thank you!


问:
Login with Facebook account not working if the facebook account registered with phone number
I have integrated "Login with Facebook" account in my website build with PHP. I used PHP SDK of Facebook. Everything worked fine until I tried to login via facebook account which was registered using mobile number. This facebook account does not have an email address added. It throws an error in facebook website & it is not redirecting to my website.

I am trying to get 'email' & 'public_profile' permissions. And I just need id & name. I am using v2.5 as default_graph_version.

I have not pasted the code here as I am very much using the SDK provided by Facebook without any changes. Please let me know if I need to paste my code here.

Here is screenshot of the error that I got.

Your help is very much appreciated.

Update: This is the code that i am using,

```<code>$fb = new Facebook\Facebook([
    'app_id' => 'APP-ID-HERE',
    'app_secret' => 'APP-SECRET-HERE',
    'default_graph_version' => 'v2.5',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email', 'public_profile'];
$loginUrl = $helper->getLoginUrl('http://my-test-domain.com/', $permissions);

echo '<a class="fb-login" href="' . htmlspecialchars($loginUrl) . '">Log in with FB</a>';  `
</code>```

Update 2: Here is App Restrictions settings in My App,

答:
For alcohol content related websites, there is an age limit which varies based on where you live. The user who is connecting via FB to a website which contains alcohol content need to be 25 years or older to use Facebook and Alchohol related apps for India & Sweden.

here the reference links,

http://help.untappd.com/discussions/social-account-issues/1466-facebook-error

https://developers.facebook.com/docs/sharing/opengraph/using-actions

Body:
I have integrated "Login with Facebook" account in my website build with PHP. I used PHP SDK of Facebook. Everything worked fine until I tried to login via facebook account which was registered using mobile number. This facebook account does not have an email address added. It throws an error in facebook website & it is not redirecting to my website.

I am trying to get 'email' & 'public_profile' permissions. And I just need id & name. I am using v2.5 as default_graph_version.

I have not pasted the code here as I am very much using the SDK provided by Facebook without any changes. Please let me know if I need to paste my code here.

Here is screenshot of the error that I got.

Your help is very much appreciated.

Update: This is the code that i am using,

$fb = new Facebook\Facebook([
    'app_id' => 'APP-ID-HERE',
    'app_secret' => 'APP-SECRET-HERE',
    'default_graph_version' => 'v2.5',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email', 'public_profile'];
$loginUrl = $helper->getLoginUrl('http://my-test-domain.com/', $permissions);

echo 'Log in with FB';  `

Update 2: Here is App Restrictions settings in My App,


问:
React CSS Modules, Is not working. Some Idea?
I install all the dependences:

```<code>    "devDependencies": {
      "css-loader": "^0.26.4",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.13.2
    }
</code>```

The bundle detect my import correctly:

```<code>import styles from './styles.scss';
</code>```

and I configure my webpack config:

```<code>module : {
    loaders : [
        {
            test: /\.(sass|scss)$/,
            use: ['style-loader', 'css-loader', 'sass-loader']
        },
        {
            test : /\.jsx?/,
            include : APP_DIR,
            loader : 'babel-loader'
        }
    ]
}
</code>```

But in the final render doesn't appear the classes.
Some idea? Thank you!!!

答:
Your jsx test value is wrong, isn't it? Has to be </p>

```<code>{
    test : /\.jsx$/,
    include : APP_DIR,
    loader : 'babel-loader'
}
</code>```

Body:
I install all the dependences:

    "devDependencies": {
      "css-loader": "^0.26.4",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.13.2
    }

The bundle detect my import correctly:

import styles from './styles.scss';

and I configure my webpack config:

module : {
    loaders : [
        {
            test: /\.(sass|scss)$/,
            use: ['style-loader', 'css-loader', 'sass-loader']
        },
        {
            test : /\.jsx?/,
            include : APP_DIR,
            loader : 'babel-loader'
        }
    ]
}

But in the final render doesn't appear the classes.
Some idea? Thank you!!!

Body:
Your jsx test value is wrong, isn't it? Has to be

{
    test : /\.jsx$/,
    include : APP_DIR,
    loader : 'babel-loader'
}


问:
Calling helper method from an admin view
```<code>Rails 3.2
</code>```

I inherited an application, architected to have both admin and non-admin sections. So, I have:

```<code>app/views/admin/....
app/views/....
app/helpers/admin/...
app/helpers/....
</code>```

I am not sure how to call helper methods from the views. Let's take an example:

In app/helpers/admin/users_helper.rb, if I have:

```<code>def compute_total qty, price, commission
  (qty * price) + commission
end
</code>```

and in app/helpers/users_helper.rb, if I have:

```<code>def compute_total qty, price
  qty * price
end
</code>```

I have two questions:

Does Rails understand which method to call, based on the location of the view the method is called from?

What I want to force call a non-admin helper, from an admin view, or a helper from an admin view? How is that done?

答:
View helper methods you write on rails are available to all views and are mixed together (starting from Rails 4). Whenever there is a duplicate in name, rails will handle this by choosing the latter method alphabetically. For example,

```<code>module CustomHelper
  def compute_total qty, price, commission
  ......
end

module KustomHelper
  def compute_total qty, price
  ......
end
</code>```

In the example above, the one that WILL always be called is the one from KustomHelper.

For your second question, what I would suggest is just use one method, that can handle both scenarios, such as this:

```<code>def compute_total(qty, price, commission = 0)
  (qty * price) + commission
end
</code>```

You can declare the method anywhere and call it anywhere, no worries.

Good reference: https://mixandgo.com/blog/the-beginners-guide-to-rails-helpers

UPDATE:

I did not see that the OP uses version below 4, so the solution for OP's particular problem:

```<code> # lib/custom_lib.rb
 class CustomLib
   def compute_total(qty, price, commission = 0)
     qty * price) + commission
   end
 end
</code>```

Then call it from the view as such:

```<code> <%= CustomLib.new.compute_total(qty, price) %>
</code>```

Body:
Rails 3.2

I inherited an application, architected to have both admin and non-admin sections. So, I have:

app/views/admin/....
app/views/....
app/helpers/admin/...
app/helpers/....

I am not sure how to call helper methods from the views. Let's take an example:

In app/helpers/admin/users_helper.rb, if I have:

def compute_total qty, price, commission
  (qty * price) + commission
end

and in app/helpers/users_helper.rb, if I have:

def compute_total qty, price
  qty * price
end

I have two questions:

Does Rails understand which method to call, based on the location of the view the method is called from?

What I want to force call a non-admin helper, from an admin view, or a helper from an admin view? How is that done?

Body:
View helper methods you write on rails are available to all views and are mixed together (starting from Rails 4). Whenever there is a duplicate in name, rails will handle this by choosing the latter method alphabetically. For example,

module CustomHelper
  def compute_total qty, price, commission
  ......
end

module KustomHelper
  def compute_total qty, price
  ......
end

In the example above, the one that WILL always be called is the one from KustomHelper.

For your second question, what I would suggest is just use one method, that can handle both scenarios, such as this:

def compute_total(qty, price, commission = 0)
  (qty * price) + commission
end

You can declare the method anywhere and call it anywhere, no worries.

Good reference: https://mixandgo.com/blog/the-beginners-guide-to-rails-helpers

UPDATE:

I did not see that the OP uses version below 4, so the solution for OP's particular problem:

 # lib/custom_lib.rb
 class CustomLib
   def compute_total(qty, price, commission = 0)
     qty * price) + commission
   end
 end

Then call it from the view as such:

 <%= CustomLib.new.compute_total(qty, price) %>


问:
Organizing script files
I usually have jQuery code that is page specific along with a handful of functions that many pages share. One approach is to make seperate files for organizing, but i'm thinking that putting all the script in one file and making comments in the file for readability would also work. Then when the site goes live I can minify and obfuscate if needed.

I think the question comes down to limiting http requests or limiting file size. Is one of these a bad habit?

答:
You can have it both ways. Develop with as many individual .js files as you need. Then use a build/deployment process that assembles the files into one larger one, then pushes them through something like Google's Closure Compiler. Compression can be handled transparently by your web server if configured properly.

Of course, this implies a structured development and deployment workflow -- e.g., with files to be assembled/compiled in a specific directory, separated from files that should be served as-is.

References:

Closure Compiler

Apache Ant

Automating the Closure Compiler with Ant

Title: Organizing script files


问:
barplot xlim shifts axis -> offset to axis at=midpoints missing
I have the following problem – it is purely an ascetic one but it bothers me that it is not looking nicely:
I generate a simple sideways barplot with ticks at the bottom of the bars. The default setting generates an x-axis which is shorter than my bars (figure 1). To solve this I included xlim. Once I do that the x-axis is slightly shifted to the left so the y-axis is touching the bars (figure 2). This does not look nice at all. I guess xlim somehow overwrite a default parameter but I could not find which. I would be grateful for any suggestions!

```<code>rm(list=ls())

data<-c(69,500,597)
names(data)<-c("text1", "text2", "text3")

midpoints<-barplot(data, beside=T, space=1, xlim=c(0,600))

filename=paste("orig.pdf", sep="")
pdf(file=filename, width=10, height =5)

par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data))
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()

filename=paste("with_limit.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(0,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim)
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()
</code>```

Figure 1

Figure 2

答:
Meanwhile I did find two possible answers both not perfect but working.
The first one is to work with xaxs="r" but for my taste now the offset is too large.

```<code>filename=paste("solution1.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(0,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim, xaxs="r")
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()
</code>```

Solution1

The second option is to have xlim starting in the negative. This has the disadvantage of tuning the offset by hand. In my case I had multiple figures and I wanted it always to be the same so I used (here) 2% of the maximum 600 -> 12. For all others I also used 2% of the maximum. That worked nicely in the end.

```<code>filename=paste("solution2.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(-12,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim)
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()
</code>```

Solution2

Body:
I have the following problem – it is purely an ascetic one but it bothers me that it is not looking nicely:
I generate a simple sideways barplot with ticks at the bottom of the bars. The default setting generates an x-axis which is shorter than my bars (figure 1). To solve this I included xlim. Once I do that the x-axis is slightly shifted to the left so the y-axis is touching the bars (figure 2). This does not look nice at all. I guess xlim somehow overwrite a default parameter but I could not find which. I would be grateful for any suggestions!

rm(list=ls())

data<-c(69,500,597)
names(data)<-c("text1", "text2", "text3")

midpoints<-barplot(data, beside=T, space=1, xlim=c(0,600))

filename=paste("orig.pdf", sep="")
pdf(file=filename, width=10, height =5)

par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data))
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()

filename=paste("with_limit.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(0,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim)
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()

Figure 1

Figure 2

Body:
Meanwhile I did find two possible answers both not perfect but working.
The first one is to work with xaxs="r" but for my taste now the offset is too large.

filename=paste("solution1.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(0,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim, xaxs="r")
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()

Solution1

The second option is to have xlim starting in the negative. This has the disadvantage of tuning the offset by hand. In my case I had multiple figures and I wanted it always to be the same so I used (here) 2% of the maximum 600 -> 12. For all others I also used 2% of the maximum. That worked nicely in the end.

filename=paste("solution2.pdf", sep="")
pdf(file=filename, width=10, height =5)

lim<-c(-12,600)
par(mar=c(4,9,1,4))
barplot(data, beside=T, xlab=expression(paste("Text")),
        axes=T, cex.lab=2, cex.axis=2, cex.names=2,  font.axis = 2,
        col=c("grey"),  horiz=T, las=1, font.lab=2,  space=1,
        names.arg=colnames(data), xlim=lim)
axis(side = 2, at = midpoints , labels = F, cex.axis=1.5)

dev.off()

Solution2


问:
Scale sprite kit game for all devices
When creating my game in spriteKit I used the game size 1080x1920. Now however If I am to run it on Ipad it looks bizarre. Is there an easy fix? I am simply worried that my app will get rejected. Thank you in advance?

答:
Its quite a commonly asked question.

What we usually do in SpriteKt is to give the SKScene a fixed size and let SpriteKit do the scaling for you on different devices.

So basically we have 2 ways to do it correctly

1) Set scene size to iPad (e.g 1024x768 -landscape, 768x1024 - portrait). This was the default setting in Xcode 7.

You than usually just have/show some extra background at the top/bottom (landscape) or left/right (portrait) on iPads which gets cropped on iPhones.

Examples of games that show more on iPads / crop on iPhones:

Altos Adventure, Leos Fortune, Limbo, The Line Zen, Modern Combat 5.

2) Apple changed the default scene size in xCode 8 to iPhone 6/7 (750*1334-Portait, 1334*750-Landscape). This setting will crop your game on iPads.

Examples of games that show less on iPads:

Lumino City, Robot Unicorn Attack

Choosing between those 2 options is up to you and depends what game you are making.

Regardless of scene size scale mode is usually best left at .aspectFill or .aspectFit, again depending on what you prefer and need (e.g cropping with aspectFill or black bars with aspectFit)

You would use the Universal asset slot and/or device specific images. This way you will have a consistent experience on all devices

Spritekit scale full game to iPad

How to make SKScene have fixed width?

Hope this helps

Title: Scale sprite kit game for all devices


问:
component service not being injected into test in jasmine
Given the following test.

The $provided service is not being injected. If I debug the test in karma I can see that the service being provided is the real one, and not the mock.

The really weird thing, is that if I remove the $provide.service... I get an error Error: [$injector:unpr] Unknown provider: ficaServiceProvider <- ficaService. This clearly means that the service is getting registered, just not replaced?

```<code>describe("component: FicaStatusComponent",
    function () {
        var fs;
        beforeEach(function () {
            module("aureus",
                function ($provide) {
                    $provide.service("ficaService", function () {
                        this.status = function () {
                            return $q(function (resolve, reject) {
                                resolve([{ documentType: { id: 1 } }]);
                            });
                        }
                    })
                });

        });

        beforeEach(inject(function (_$componentController_, _ficaService_) {
            $componentController = _$componentController_;
            fs = _ficaService_;
        }));

        it("should expose a `fica` object", function () {
            console.log('should expose');
            var bindings = {};
            var ctrl = $componentController("ficaStatus", null, bindings);
            expect(ctrl.fica).toBeDefined();
        });

        it("compliant with no documents should not be compliant",
            function () {
                var ctrl = $componentController("ficaStatus");
                expect(ctrl.fica.length).toEqual(1);
            });
    }
);
</code>```

The second test compliant with no documents... is failing.

Chrome 56.0.2924 (Windows 10 0.0.0) component: FicaStatusComponent compliant with no documents should not be compliant FAILED
          Error: Unexpected request: GET api/fica/status/

I have also tried this, expecting to have an empty object injected, but the "real" service is there nevertheless?

```<code>        module("aureus", function($provide) {
            $provide.value("ficaService", function() { return {}; });
            $provide.service("ficaService", function() { return {}; });
        });
</code>```

Here is the implementation of the controller for the component:

```<code>var FicaStatusController = (function () {
    function FicaStatusController($log, $loc, ficaService) {
        var _this = this;
        this.$log = $log;
        this.$loc = $loc;
        this.ficaService = ficaService;
        this.fica = [];
        this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
    }

FicaStatusController.$inject = ["$log", "$location", "IFicaStatusService"];
module("aureus").component("ficaStatus", new FicaStatusComponent());
module("aureus").service("IFicaStatusService", FicaStatusService);
</code>```

The service is as follows:

```<code>var FicaStatusService = (function () {
    function FicaStatusService($log, $http) {
        this.$log = $log;
        this.$http = $http;
    }
    FicaStatusService.prototype.status = function (accountNumber) {
        var url = "api/fica/status/" + accountNumber;
        this.$log.log("status: " + url);
        return this.$http
            .get(url)
            .then(function (_) { return _.data; });
    };
    return FicaStatusService;
}());

...
</code>```

答:
You have added your service in your module like this:

module("aureus").service("IFicaStatusService", FicaStatusService);

That means that you will need to provide IFicaStatusService instead of ficaService with $provide.

Body:
Given the following test.

The $provided service is not being injected. If I debug the test in karma I can see that the service being provided is the real one, and not the mock.

The really weird thing, is that if I remove the $provide.service... I get an error Error: [$injector:unpr] Unknown provider: ficaServiceProvider <- ficaService. This clearly means that the service is getting registered, just not replaced?

describe("component: FicaStatusComponent",
    function () {
        var fs;
        beforeEach(function () {
            module("aureus",
                function ($provide) {
                    $provide.service("ficaService", function () {
                        this.status = function () {
                            return $q(function (resolve, reject) {
                                resolve([{ documentType: { id: 1 } }]);
                            });
                        }
                    })
                });

        });

        beforeEach(inject(function (_$componentController_, _ficaService_) {
            $componentController = _$componentController_;
            fs = _ficaService_;
        }));

        it("should expose a `fica` object", function () {
            console.log('should expose');
            var bindings = {};
            var ctrl = $componentController("ficaStatus", null, bindings);
            expect(ctrl.fica).toBeDefined();
        });

        it("compliant with no documents should not be compliant",
            function () {
                var ctrl = $componentController("ficaStatus");
                expect(ctrl.fica.length).toEqual(1);
            });
    }
);

The second test compliant with no documents... is failing.

Chrome 56.0.2924 (Windows 10 0.0.0) component: FicaStatusComponent compliant with no documents should not be compliant FAILED
          Error: Unexpected request: GET api/fica/status/

I have also tried this, expecting to have an empty object injected, but the "real" service is there nevertheless?

        module("aureus", function($provide) {
            $provide.value("ficaService", function() { return {}; });
            $provide.service("ficaService", function() { return {}; });
        });

Here is the implementation of the controller for the component:

var FicaStatusController = (function () {
    function FicaStatusController($log, $loc, ficaService) {
        var _this = this;
        this.$log = $log;
        this.$loc = $loc;
        this.ficaService = ficaService;
        this.fica = [];
        this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
    }

FicaStatusController.$inject = ["$log", "$location", "IFicaStatusService"];
module("aureus").component("ficaStatus", new FicaStatusComponent());
module("aureus").service("IFicaStatusService", FicaStatusService);

The service is as follows:

var FicaStatusService = (function () {
    function FicaStatusService($log, $http) {
        this.$log = $log;
        this.$http = $http;
    }
    FicaStatusService.prototype.status = function (accountNumber) {
        var url = "api/fica/status/" + accountNumber;
        this.$log.log("status: " + url);
        return this.$http
            .get(url)
            .then(function (_) { return _.data; });
    };
    return FicaStatusService;
}());

...


问:
This.setState causes the browser to hang + Reactjs
```<code>var columns = []
    for (var key in this.props.col)
    {
        if (this.state.isEditing){
            columns.push(<td key = {key.id}><input ref = "txt" type = "text" value = { this.state.itemValue } onChange = { this.onTextChange.bind(this) } /></td>)
        }
        else
        {
            columns.push(<td key = {key.id}>{ this.props.col[key] }</td>)
            // this.setState({
            //  itemValue: key,
            //  isEditing: false
            // })
            console.log(key)
        }
        console.log(key);
    }
    return columns
</code>```

Every time I uncomment this lines:

```<code>// this.setState({
            //  itemValue: key,
            //  isEditing: false
            // })
</code>```

It causes the browser to hang. And a modal message shows up on the browser which says "a script on this page may be busy" and asking me whether to stop the script or continue. Thanks.

答: Every time you 'setState', your component will rerender, and I guess your function is called during the rendering phase (since it seems to build columns)</p>

Body:
var columns = []
    for (var key in this.props.col)
    {
        if (this.state.isEditing){
            columns.push(<input ref = "txt" type = "text" value = { this.state.itemValue } onChange = { this.onTextChange.bind(this) } />	)
        }
        else
        {
            columns.push({ this.props.col[key] }	)
            // this.setState({
            //  itemValue: key,
            //  isEditing: false
            // })
            console.log(key)
        }
        console.log(key);
    }
    return columns

Every time I uncomment this lines:

// this.setState({
            //  itemValue: key,
            //  isEditing: false
            // })

It causes the browser to hang. And a modal message shows up on the browser which says "a script on this page may be busy" and asking me whether to stop the script or continue. Thanks.


问:
Two database connect in laravel
How to connect two database in laravel-5 and how to get data from db.

I know two one thing for that

In config/database set like this.

```<code>    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'larashop'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

 'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'larashop2'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
</code>```

答:
I have find the issue of connect 2 database in laravel.

If any body wants two work with 2 database then config as par above suggestion and remove database configuration from .env file which is located at root.

I have tried and I am working with 2 database.

Title: Two database connect in laravel

Body:
How to connect two database in laravel-5 and how to get data from db.

I know two one thing for that

In config/database set like this.

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'larashop'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

 'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'larashop2'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],


问:
What is the main idea of OpenFOAM?
I just want to get the main idea/principle of openFOAM and how you create a simulation, please let me know where I go wrong,
So basically you have a object that interacts with gas or liquid and you want to simulate this, so you create model of the object, mesh it, specify where the gas will flow in and out and what are the walls, and set the other correct parameters and then run the program (with the approprate time step etc)?</p>

答: OpenFOAM is an open source C++ library which implements the finite volume method (FVM), which is widely used in CFD.</p>

Title: What is the main idea of OpenFOAM?


问:
How insert in database using insert query(mysql) in php
ककखघगघचछजझ़ंंनधथतणढठटपफफबभमयरलवशश्ँत्रत्रक्षससज्ञाइइईउऊ चजझ़ंनधदथतणढठट पबभमययलवशश ँऋत्रक्षहसषर्टाइउए 123455678990१२३४५६७८९० @()"'-/?₹_+×÷¡¿√♀•∆π™℅¶♂♀【】°℃®©★■◆●

how to insert Smiley and text in database using mysql insert query and so on .

I want to use this in Rest api webservice for mobile app.

答:
Alter the column of table or alter the table</p>

```<code>ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
</code>```

Body:
Alter the column of table or alter the table

ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin


问:
(Python/Django/MySQL) Issue with updating form table in HTML page without using php
I'm a newbie on Python and Django here, I was tasked to create and update a form table in a HTML page using Django and MySQL database without using PHP, I manage to create and display the data but I'm having trouble on the editing/updating part.

How can I do it without using PHP? I'm having trouble understanding on how to use UpdateView. Also I'm trying using 2 ways for user to submit the updated table,

1) by pressing enter 2) by pressing the submit button

Below is my code, I try to use the same code as the one I use to GET the data from input box into the database, but for this it just append another row I last add into the database instead of editing it. I also use dhtmlx to design the table. I've been stuck doing this for days and I really appreciate everyone input in this, Thanks a bunch and apologies for the cluttered codes.

model.py

```<code>from django.db import models

class UserInfo(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    employee_id = models.CharField(max_length=10)
    gender = models.CharField(max_length=12)

    def __str__(self):
        return self.first_name
</code>```

view.py

```<code>from django.shortcuts import render
from .form import UserDisplayInfoForm
from .models import UserInfo

def display_view(request, id=None):
    display_table = UserInfo.objects.all()
    if request.method == 'POST':
        print(request.POST)
        form = UserDisplayInfoForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            form.save()
return render(request, 'myform/display.html',
{"display_table": display_table}, {'form': UserDisplayInfoForm,})
</code>```

form.py

```<code>from django import forms
from .models import UserInfo
from django.views.generic.edit import UpdateView

class UserDisplayInfoForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        template_name = 'myform/display.html'
        fields = [
            "first_name",
            "last_name",
            "employee_id",
            "gender"
        ]
</code>```

urls.py

```<code>from django.conf.urls import url
from django.contrib import admin
from myform import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index_view),
    url(r'^display/', views.display_view)
]
</code>```

display.html

```<code><html>
    <head>
    <title> Lemonsky  v 0.0.1 </title>
    <link rel="stylesheet" type="text/css" href="static/css/roboto.css"/>
    <link rel="stylesheet" href="http://cdn.dhtmlx.com/edge/dhtmlx.css" type="text/css">
    <script src="http://cdn.dhtmlx.com/edge/dhtmlx.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    </head>
    <body>
        <h1>Display Table</h1>
        <h2>Lemonsky  v 0.0.1 </h2>

        <form method="POST" action=""><input type='hidden'/>{% csrf_token %}
            <table class="dhtmlxGrid" id="table_data" name="grid2" gridHeight="auto" style="width:400px" imgpath="myform/static/imgs/" border="1" lightnavigation="true">
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Employee Id</th>
                        <th>Gender</th>
                    </tr>
                {% for data in display_table %}
                    <tr>
                        <td id="id_first_name" name="first_name"><input type="text" name="first_name" maxlength="30" required id="id_first_name" value="{{data.first_name}}"/></td>
                        <td id="id_last_name" name="last_name"><input type="text" name="last_name" maxlength="30" required id="id_last_name" value="{{data.last_name}}"/></td>
                        <td id="id_employee_id" name="employee_id"><input type="text" name="employee_id" maxlength="10" required id="id_employee_id" value="{{data.employee_id}}"/></td>
                        <td id="gender" name="gender"><input type="text" name="gender" maxlength="10" required id="id_gender" value="{{data.gender}}"/></td>
                    </tr>
                {% endfor %}
            </table>

            <input type='submit' value='submit'/>
        </form>
        <script type="text/javascript">
            $(document).ready(function(){
                $("td").keydown(function(event){
                    var keycode = event.keyCode || event.which;

                        if(keycode == 13){
                            var td_value = $(this).children(':nth-child(1)').val()
                            console.log(td_value);
                            alert(td_value);
                            <!--$.post(URL, data, function(response))-->
                        }
                });
            });
        </script>
    </body>
</html>
</code>```

答:
You are all the time inserting into the DB new objects.

You should first query if the object exist in the database. Like Select * from UserInfo where first_name = "test" but done with Django ORM. Pay attention to do a select with unique id, first_name may not be unique and this is an example.

```<code>def display_view(request, id=None):
    display_table = UserInfo.objects.all()
    if request.method == 'POST':
        first_name = request.POST.get("first_name", "")
        user = UserInfo.objects.get(first_name = first_name)
        if user:
            form = UserDisplayInfoForm(instance=user)
        else:
            form = UserDisplayInfoForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            form.save()
return render(request, 'myform/display.html',
{"display_table": display_table}, {'form': UserDisplayInfoForm,})
</code>```

Body:
I'm a newbie on Python and Django here, I was tasked to create and update a form table in a HTML page using Django and MySQL database without using PHP, I manage to create and display the data but I'm having trouble on the editing/updating part.

How can I do it without using PHP? I'm having trouble understanding on how to use UpdateView. Also I'm trying using 2 ways for user to submit the updated table,

1) by pressing enter 2) by pressing the submit button

Below is my code, I try to use the same code as the one I use to GET the data from input box into the database, but for this it just append another row I last add into the database instead of editing it. I also use dhtmlx to design the table. I've been stuck doing this for days and I really appreciate everyone input in this, Thanks a bunch and apologies for the cluttered codes.

model.py

from django.db import models

class UserInfo(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    employee_id = models.CharField(max_length=10)
    gender = models.CharField(max_length=12)

    def __str__(self):
        return self.first_name

view.py

from django.shortcuts import render
from .form import UserDisplayInfoForm
from .models import UserInfo

def display_view(request, id=None):
    display_table = UserInfo.objects.all()
    if request.method == 'POST':
        print(request.POST)
        form = UserDisplayInfoForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            form.save()
return render(request, 'myform/display.html',
{"display_table": display_table}, {'form': UserDisplayInfoForm,})

form.py

from django import forms
from .models import UserInfo
from django.views.generic.edit import UpdateView

class UserDisplayInfoForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        template_name = 'myform/display.html'
        fields = [
            "first_name",
            "last_name",
            "employee_id",
            "gender"
        ]

urls.py

from django.conf.urls import url
from django.contrib import admin
from myform import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index_view),
    url(r'^display/', views.display_view)
]

display.html

    <title> Lemonsky  v 0.0.1 </title>
    <link rel="stylesheet" type="text/css" href="static/css/roboto.css"/>
    <link rel="stylesheet" href="http://cdn.dhtmlx.com/edge/dhtmlx.css" type="text/css">

Display Table

Lemonsky  v 0.0.1

        <form method="POST" action=""><input type='hidden'/>{% csrf_token %}

                        First Name
                        Last Name
                        Employee Id
                        Gender

                {% for data in display_table %}

                        <input type="text" name="first_name" maxlength="30" required id="id_first_name" value="{{data.first_name}}"/>
                        <input type="text" name="last_name" maxlength="30" required id="id_last_name" value="{{data.last_name}}"/>
                        <input type="text" name="employee_id" maxlength="10" required id="id_employee_id" value="{{data.employee_id}}"/>
                        <input type="text" name="gender" maxlength="10" required id="id_gender" value="{{data.gender}}"/>

                {% endfor %}

            <input type='submit' value='submit'/>
        </form>

Body:
You are all the time inserting into the DB new objects.

You should first query if the object exist in the database. Like Select * from UserInfo where first_name = "test" but done with Django ORM. Pay attention to do a select with unique id, first_name may not be unique and this is an example.

def display_view(request, id=None):
    display_table = UserInfo.objects.all()
    if request.method == 'POST':
        first_name = request.POST.get("first_name", "")
        user = UserInfo.objects.get(first_name = first_name)
        if user:
            form = UserDisplayInfoForm(instance=user)
        else:
            form = UserDisplayInfoForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            form.save()
return render(request, 'myform/display.html',
{"display_table": display_table}, {'form': UserDisplayInfoForm,})