问:
Are there any performance or coding issues with passing an object to multiple pages as a way to share variables for tabbed pages?
I am using a tabbed page like this:

```<code>public partial class MainPage : TabbedPage
{

    public MainPage()
    {
        InitializeComponent();

        var phrasesPage = new NavigationPage(new PhrasesPage())
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }
</code>```

I want to share variables between my pages. For example a score number that will show on all pages and a few other variables.

I would like to code my application so that it's easy to maintain.

```<code>public partial class MainPage : TabbedPage
{

   public class Person
   {
       public string Name { get; set; }
       public int Age { get; set; }
       public Person(){}
       public Person(string name, int age)
       {
           Name = name;
           Age = age;
       }
    }

    public MainPage()
    {
        InitializeComponent();

        var person = Person p=new Person()
        {
           Name = "Han Solo",
           Age = 39
        };

        var phrasesPage = new NavigationPage(new PhrasesPage(person))
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }
</code>```

Can someone advise me if it would be good to create an object that contains all the shared variables and then to pass that object to the constructor of each of the pages as a parameter when the pages are created with a "new"?

答:
However you could pass it every time to a constructor, I think it would be better to create a static Singleton class to store the 'shared' values in. Than you don't always have to pass it but you just have to make a call to the class to fill/get values

A bit more information about singletons / static classes: https://www.dotnetperls.com/singleton-static

An example:

The static class where we going to keep our values in:
 public static class Test
    {

```<code>    public static Person person;

    static Test()
    {

    }

    public static void ResetValues() {
        person= new Person();
    }
}
</code>```

Than in your mainpage (don't forget to add using static Test(=Name of class)) :

```<code>public MainPage()
    {
        InitializeComponent();
//person --> comes from the static class

     person=new Person()
    {
       Name = "Han Solo",
       Age = 39
    };

    var phrasesPage = new NavigationPage(new PhrasesPage())
    {
        Title = "Play",
        Icon = "play.png"
    };
    ....
    ....
    Children.Add(phrasesPage);
    Children.Add(categoriesPage);
    Children.Add(favoritesPage);
    Children.Add(settingsPage);
    Children.Add(aboutPage);
}
</code>```

Than you can acces han solo from anyway ( just call person from the static class)

Body:
I am using a tabbed page like this:

public partial class MainPage : TabbedPage
{

    public MainPage()
    {
        InitializeComponent();

        var phrasesPage = new NavigationPage(new PhrasesPage())
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }

I want to share variables between my pages. For example a score number that will show on all pages and a few other variables.

I would like to code my application so that it's easy to maintain.

public partial class MainPage : TabbedPage
{

   public class Person
   {
       public string Name { get; set; }
       public int Age { get; set; }
       public Person(){}
       public Person(string name, int age)
       {
           Name = name;
           Age = age;
       }
    }

    public MainPage()
    {
        InitializeComponent();

        var person = Person p=new Person()
        {
           Name = "Han Solo",
           Age = 39
        };

        var phrasesPage = new NavigationPage(new PhrasesPage(person))
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }

Can someone advise me if it would be good to create an object that contains all the shared variables and then to pass that object to the constructor of each of the pages as a parameter when the pages are created with a "new"?

Body:
However you could pass it every time to a constructor, I think it would be better to create a static Singleton class to store the 'shared' values in. Than you don't always have to pass it but you just have to make a call to the class to fill/get values

A bit more information about singletons / static classes: https://www.dotnetperls.com/singleton-static

An example:

The static class where we going to keep our values in:
 public static class Test
    {

    public static Person person;

    static Test()
    {

    }

    public static void ResetValues() {
        person= new Person();
    }
}

Than in your mainpage (don't forget to add using static Test(=Name of class)) :

public MainPage()
    {
        InitializeComponent();
//person --> comes from the static class

     person=new Person()
    {
       Name = "Han Solo",
       Age = 39
    };

    var phrasesPage = new NavigationPage(new PhrasesPage())
    {
        Title = "Play",
        Icon = "play.png"
    };
    ....
    ....
    Children.Add(phrasesPage);
    Children.Add(categoriesPage);
    Children.Add(favoritesPage);
    Children.Add(settingsPage);
    Children.Add(aboutPage);
}

Than you can acces han solo from anyway ( just call person from the static class)


来源: stackexchange

问:
How do I use external assemblies with Microsoft Azure Function Apps?
The documentation says that you can put a DLL in a bin folder and reference it using a special #r syntax, however in the Azure portal I cannot find how to upload these DLLs. Is this possible, and if so, how is that supposed to be accomplished?

答:
You can use Octopus Deploy (Website deployment step) to deploy a function.

The folder structure of the nuget package pushed to octopus deploy should be:

```<code>nuget_package.nupkg
    |--bin
        |--*.dll
    |--run.csx
    |--function.json
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use Octopus Deploy (Website deployment step) to deploy a function.

The folder structure of the nuget package pushed to octopus deploy should be:

nuget_package.nupkg
    |--bin
        |--*.dll
    |--run.csx
    |--function.json


问:
Error when trying to execute User Defined Functions in Pyspark over a Dataframe
I am creating a little program in Pyspark in which I want to generate a Used Defined Function to call 'method1' from a lambda function into 'method0'.

I simplified de code to a better understanding, but the core functionality would be: for each instance in a dataframe, the 'method0' applies 'method1' (with the help of a lambda function) to return a value according to the values of the instance that is inspecting have. This way, if the first condition of  'method1' is met, the value for that instance should be '-', but if not, it shoud be 'other'.

With those operations, the idea is to get a column from that UDF and attach it to the dataframe in 'method0'. Here is the modified code for you to easier understand it:

```<code>def method1(atr_list, instance, ident):

    if(instance.ATR1 != '-'):
        return instance.ATR1
    else:
        # Other operations ...
        return 'other'

def method0(df, atr_example_list, ident):

    udf_func = udf(lambda instance: method1(atr_example_list, instance, ident), returnType=StringType())
    new_column = udf_func(df)
    df = df.withColumnRenamed("New_Column", new_column)
    return df

result = method0(df, list, "1111")
</code>```

But when I execute this code, I get the next error and I don't really know why:

```<code>Py4JError: An error occurred while calling o298.__getnewargs__. Trace:
py4j.Py4JException: Method __getnewargs__([]) does not exist
at
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
at
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
at py4j.Gateway.invoke(Gateway.java:272)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:748)
</code>```

Here is an example of input and the output I expect:

Dataframe 'df':

```<code>+-------+-------+-------+
| ATR1  |  ATR2 | ATRN  |
+-------+-------+-------+
| '-'   |   1   |  'a'  |
| '-'   |   1   |  'a'  |
| '-'   |   2   |  'b'  |
| '++'  |   1   |  'a'  |
+-------+-------+-------+
</code>```

Passing the dataframe 'df' as a parameter to 'method0' (not necessary to take a look at parameters 'atr_example_list' and 'ident' for this simplified example) I want to get a column like this on 'method1' calling:

```<code>+------------+
| new_column |
+------------+
|   'other'  |
|   'other'  |
|   'other'  |
|    '++'    |
+------------+
</code>```

So on method0, the new dataframe would be:

```<code>+-------+-------+-------+------------+
| ATR1  |  ATR2 | ATRN  | new_column |
+-------+-------+-------+------------+
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   2   |  'b'  |   'other'  |
| '++'  |   1   |  'a'  |    '++'    |
+-------+-------+-------+------------+
</code>```

Could anyone help me?

答:
Can't you simplify and use a single udf like that (method1 can take more than one column if necessary) ? : </p>

```<code>def method1(x):
  if x != "-":
    return x
  else:
    return 'other'

u_method1 = udf(method1, StringType())

result = df.withColumn("new_column", u_method1("ATR1"))
</code>```

Body:
I am creating a little program in Pyspark in which I want to generate a Used Defined Function to call 'method1' from a lambda function into 'method0'.

I simplified de code to a better understanding, but the core functionality would be: for each instance in a dataframe, the 'method0' applies 'method1' (with the help of a lambda function) to return a value according to the values of the instance that is inspecting have. This way, if the first condition of  'method1' is met, the value for that instance should be '-', but if not, it shoud be 'other'.

With those operations, the idea is to get a column from that UDF and attach it to the dataframe in 'method0'. Here is the modified code for you to easier understand it:

def method1(atr_list, instance, ident):

    if(instance.ATR1 != '-'):
        return instance.ATR1
    else:
        # Other operations ...
        return 'other'

def method0(df, atr_example_list, ident):

    udf_func = udf(lambda instance: method1(atr_example_list, instance, ident), returnType=StringType())
    new_column = udf_func(df)
    df = df.withColumnRenamed("New_Column", new_column)
    return df

result = method0(df, list, "1111")

But when I execute this code, I get the next error and I don't really know why:

Py4JError: An error occurred while calling o298.__getnewargs__. Trace:
py4j.Py4JException: Method __getnewargs__([]) does not exist
at
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
at
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
at py4j.Gateway.invoke(Gateway.java:272)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:748)

Here is an example of input and the output I expect:

Dataframe 'df':

+-------+-------+-------+
| ATR1  |  ATR2 | ATRN  |
+-------+-------+-------+
| '-'   |   1   |  'a'  |
| '-'   |   1   |  'a'  |
| '-'   |   2   |  'b'  |
| '++'  |   1   |  'a'  |
+-------+-------+-------+

Passing the dataframe 'df' as a parameter to 'method0' (not necessary to take a look at parameters 'atr_example_list' and 'ident' for this simplified example) I want to get a column like this on 'method1' calling:

+------------+
| new_column |
+------------+
|   'other'  |
|   'other'  |
|   'other'  |
|    '++'    |
+------------+

So on method0, the new dataframe would be:

+-------+-------+-------+------------+
| ATR1  |  ATR2 | ATRN  | new_column |
+-------+-------+-------+------------+
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   2   |  'b'  |   'other'  |
| '++'  |   1   |  'a'  |    '++'    |
+-------+-------+-------+------------+

Could anyone help me?

Body:
Can't you simplify and use a single udf like that (method1 can take more than one column if necessary) ? :

def method1(x):
  if x != "-":
    return x
  else:
    return 'other'

u_method1 = udf(method1, StringType())

result = df.withColumn("new_column", u_method1("ATR1"))


问:
Spring Data Mongo returns lists instead of string
In my Spring Boot application, I am querying a collection of documents. I'm trying to perform an aggregate operation, to group similar fields together and count them.

The issue is that while the right values are being returned, they should be just normal strings "[ \"Test Name\"]" should be "Test Name"

I can solve this issue for one of the fields by using the @Id annotation but spring data Mongo does not like composite keys so I can not use that as a solution.

How can I return just the string value and not the values that are given below.

```<code>{
    "exampleDateTime": 1392029442389,
    "exampleName": "[ \"Test Name\"]",
    "exampleDescription": "[ \"Test Description\"]",
    "exampleCount": 1
}
</code>```

So I have a java object like this

```<code>@Document(collection = "ExampleCollection")
public class Example{
    private Date exampleDateTime;
    private String exampleName;
    private String exampleDescription;
    private int exampleCount;

    ...getters and setters...
}
</code>```

The Repository Implementation with Aggregation

```<code>    public class ExampleRepositoryImpl implements ExampleRepositoryCustom {

     @Autowired
     MongoTemplate mongoTemplate;

    @Override
    public List<Example> countExampleByName() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.group("exampleName").addToSet("exampleName").as("exampleName").addToSet("exampleDateTime").as("exampleDateTime")
                .addToSet("exampleDescription").as("exampleDescription").count().as("exampleCount")

        AggregationResults<Example> groupResults = mongoTemplate.aggregate(
                aggregation,"ExampleCollection", Example.class);

        List<Example> result = groupResults.getMappedResults();
        return result;
    }
}
</code>```

答:
When you use addToSet, which returns collection type, spring calls toString() to convert it to string type ( note the quotes around [] ) as defined in your pojo

Replace your aggregation to use first with

```<code>Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.group("exampleName")
           .first("exampleName").as("exampleName")
           .first("exampleDateTime").as("exampleDateTime")
           .first("exampleDescription").as("exampleDescription")
           .count().as("exampleCount")
</code>```

OR

Change your types in pojo to String[] or collection of string if you need to use addToSet

Body:
In my Spring Boot application, I am querying a collection of documents. I'm trying to perform an aggregate operation, to group similar fields together and count them.

The issue is that while the right values are being returned, they should be just normal strings "[ \"Test Name\"]" should be "Test Name"

I can solve this issue for one of the fields by using the @Id annotation but spring data Mongo does not like composite keys so I can not use that as a solution.

How can I return just the string value and not the values that are given below.

{
    "exampleDateTime": 1392029442389,
    "exampleName": "[ \"Test Name\"]",
    "exampleDescription": "[ \"Test Description\"]",
    "exampleCount": 1
}

So I have a java object like this

@Document(collection = "ExampleCollection")
public class Example{
    private Date exampleDateTime;
    private String exampleName;
    private String exampleDescription;
    private int exampleCount;

    ...getters and setters...
}

The Repository Implementation with Aggregation

    public class ExampleRepositoryImpl implements ExampleRepositoryCustom {

     @Autowired
     MongoTemplate mongoTemplate;

    @Override
    public List<Example> countExampleByName() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.group("exampleName").addToSet("exampleName").as("exampleName").addToSet("exampleDateTime").as("exampleDateTime")
                .addToSet("exampleDescription").as("exampleDescription").count().as("exampleCount")

        AggregationResults<Example> groupResults = mongoTemplate.aggregate(
                aggregation,"ExampleCollection", Example.class);

        List<Example> result = groupResults.getMappedResults();
        return result;
    }
}

Body:
When you use addToSet, which returns collection type, spring calls toString() to convert it to string type ( note the quotes around [] ) as defined in your pojo

Replace your aggregation to use first with

Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.group("exampleName")
           .first("exampleName").as("exampleName")
           .first("exampleDateTime").as("exampleDateTime")
           .first("exampleDescription").as("exampleDescription")
           .count().as("exampleCount")

OR

Change your types in pojo to String[] or collection of string if you need to use addToSet


问:
Mutating func with external detection which variable to mutate
I have a struct with 2 variables. This struct has mutating function, but in this function I need to check, which variable to mutate. For this I use separate class' static function with complex logic. This class works with different structs, so for DRY purpose I can't represent this logic in all these structs.

The problem is, that I don't know how to receive the same struct's variable from this separate class, so no struct's variables are mutate. I think, that I miss some Swift knowledge, because I'm sure, that it is possible, without duplicating logic.

Code to represent it in Playground:

```<code>struct SomeStruct {
    var a = "a"
    var b = "b"

    mutating func mutateString(to newString: String) {
        var varToMutate = VariableDetector.whichVarToMutate(a, b)
        varToMutate = newString

        // prints to represent question
        print("varToMutate: \(varToMutate)")
        print("a: \(a)")
        print("b: \(b)")
    }
}

class VariableDetector {
    static func whichVarToMutate(_ first: String, _ second: String) -> String {
        var firstOrSecondString = ""

        // simple logic to represent question, in real case it is far more complex
        if first == "a" {
            firstOrSecondString = first
        } else {
            firstOrSecondString = second
        }

        return firstOrSecondString
    }
}

var someStruct = SomeStruct()
someStruct.mutateString(to: "c")
</code>```

This code produces:

```<code>varToMutate: c
a: a
b: b
</code>```

Yes, it can be solved with:

```<code>if varToMutate == a {
    a = newString
} else if varToMutate == b {
    b = newString
}
</code>```

But I want to solve it in more elegant way :)

Thanks for any help!

答: Unless a and b are instances of a class, your varToMutate will only be a copy, because everything besides a Class is a value-type in Swift. Maybe try UnsafeMutablePointer<T>?

Body:
I have a struct with 2 variables. This struct has mutating function, but in this function I need to check, which variable to mutate. For this I use separate class' static function with complex logic. This class works with different structs, so for DRY purpose I can't represent this logic in all these structs.

The problem is, that I don't know how to receive the same struct's variable from this separate class, so no struct's variables are mutate. I think, that I miss some Swift knowledge, because I'm sure, that it is possible, without duplicating logic.

Code to represent it in Playground:

struct SomeStruct {
    var a = "a"
    var b = "b"

    mutating func mutateString(to newString: String) {
        var varToMutate = VariableDetector.whichVarToMutate(a, b)
        varToMutate = newString

        // prints to represent question
        print("varToMutate: \(varToMutate)")
        print("a: \(a)")
        print("b: \(b)")
    }
}

class VariableDetector {
    static func whichVarToMutate(_ first: String, _ second: String) -> String {
        var firstOrSecondString = ""

        // simple logic to represent question, in real case it is far more complex
        if first == "a" {
            firstOrSecondString = first
        } else {
            firstOrSecondString = second
        }

        return firstOrSecondString
    }
}

var someStruct = SomeStruct()
someStruct.mutateString(to: "c")

This code produces:

varToMutate: c
a: a
b: b

Yes, it can be solved with:

if varToMutate == a {
    a = newString
} else if varToMutate == b {
    b = newString
}

But I want to solve it in more elegant way :)

Thanks for any help!


问:
How to force "git commit -m" to open editor
I am implementing the git template commit message for the team.
I've done it through .git/hooks/prepare-commit-msg hook by
adding one line:

cat ".gitmessage" >> "$1"

Also I've configured the below:

git config --local commit.template .gitmessage

Well, the template feature works fine but only when git commit is called
without -m flag.

Unfortunately, all the team members work flow is:

```<code>git add ...
git commit -m "Some message"
</code>```

Question: How to force git to always open the editor to edit the message,
even when called by git commit -m ... command?

答:
You can modify the commit-msg pre-hook to achieve this. For instance, you can check the number of lines in the commit message (check example below); use some regular expressions to check if the template is respected; etc.

```<code>#!/bin/bash

# Check if the number of lines is greater than 3
commit_msg_file="${1}"
minimum_lines=3
num_lines=$(wc -l "${commit_msg_file}" | cut -f1 -d' ')

if (( $num_lines < $minimum_lines )); then
    echo >&2 "Error!"
    exit 1
fi
</code>```

Check this and this for reference.

Body:
I am implementing the git template commit message for the team.
I've done it through .git/hooks/prepare-commit-msg hook by
adding one line:

cat ".gitmessage" >> "$1"

Also I've configured the below:

git config --local commit.template .gitmessage

Well, the template feature works fine but only when git commit is called
without -m flag.

Unfortunately, all the team members work flow is:

git add ...
git commit -m "Some message"

Question: How to force git to always open the editor to edit the message,
even when called by git commit -m ... command?

Body:
You can modify the commit-msg pre-hook to achieve this. For instance, you can check the number of lines in the commit message (check example below); use some regular expressions to check if the template is respected; etc.

#!/bin/bash

# Check if the number of lines is greater than 3
commit_msg_file="${1}"
minimum_lines=3
num_lines=$(wc -l "${commit_msg_file}" | cut -f1 -d' ')

if (( $num_lines < $minimum_lines )); then
    echo >&2 "Error!"
    exit 1
fi

Check this and this for reference.


问:
How to detect build time in grails? Also, specify commit revision while building war
I have to display few deployment level parameters from the running app without using external database. First one is the war build date time. Is there any way that my tomcat deployed grails application know when the build was made?

Also, Is there any way through which we can specify commit revision for the war which can then be read by application? The script for reading revision number is external task but what I am concerned about is passing this value while building war automatically and application reading it when deployed.

答:
The above answer is for grails2, however any one looking for a grails 3 solution can use the buildProperties task

```<code>buildProperties {
    inputs.property("info.app.build.date", new Date().format('yyyy-MM-dd HH:mm:ss'))
}
</code>```

It will get added to war at meta-info/grails.build.info file

The same approach can be used for git commit or any other details.

See this article How to add build date and other custom information to grails war

Body:
The above answer is for grails2, however any one looking for a grails 3 solution can use the buildProperties task

buildProperties {
    inputs.property("info.app.build.date", new Date().format('yyyy-MM-dd HH:mm:ss'))
}

It will get added to war at meta-info/grails.build.info file

The same approach can be used for git commit or any other details.

See this article How to add build date and other custom information to grails war


问:
AngularJS ng-repeat with checkbox and filter
I have ng-repeat list, and I need to filter that list with checkbox. In checkbox I have three value, ERROR, WARNING, SUCCESS. If I check ERROR, show only error, if I check ERROR and WARNING show error and warning, same with success. But problem is, when I check ERROR box, list show only data with error, but when I check WARNING, they show all data in list, not only ERROR and WARNING data. For better explanation here is </p>

```<code>> http://jsfiddle.net/ADukg/12574/
</code>```

答:
It's because of your toggleFilter() function

```<code> $scope.toggleFilter= function(filterValues) {
    if ($scope.filterValue == undefined) {
        $scope.filterValue = filterValues;
    } else {
        delete $scope.filterValue;
    }
};
</code>```

What is does:

When there is no filter, set the selected filter

When there is a filter, delete the current filter

So when you check ERROR, it sets ERROR as filter, but when you then click WARNING too, it triggers the else, and removes the current selection.

When you change your else to:

```<code>else {
    delete $scope.filterValue;
    console.log($scope.filterValue);
}
</code>```

You can see it logs undefined when selecting more than 1 filter.

Body:
I have ng-repeat list, and I need to filter that list with checkbox. In checkbox I have three value, ERROR, WARNING, SUCCESS. If I check ERROR, show only error, if I check ERROR and WARNING show error and warning, same with success. But problem is, when I check ERROR box, list show only data with error, but when I check WARNING, they show all data in list, not only ERROR and WARNING data. For better explanation here is

> http://jsfiddle.net/ADukg/12574/

Body:
It's because of your toggleFilter() function

 $scope.toggleFilter= function(filterValues) {
    if ($scope.filterValue == undefined) {
        $scope.filterValue = filterValues;
    } else {
        delete $scope.filterValue;
    }
};

What is does:

When there is no filter, set the selected filter

When there is a filter, delete the current filter

So when you check ERROR, it sets ERROR as filter, but when you then click WARNING too, it triggers the else, and removes the current selection.

When you change your else to:

else {
    delete $scope.filterValue;
    console.log($scope.filterValue);
}

You can see it logs undefined when selecting more than 1 filter.


问:
AngularJS, mdList, ng-repeat and generators
Generator:

```<code>$scope.inside = [...];

var generator        = function*() {
    var l = Math.ceil($scope.inside.length / 3);
    for (var i = 0; i < 3; i++) {
        yield $scope.inside.slice(l * i, l * (i + 1));
    }
};
$scope.insideDivided = generator();
</code>```

Template:

```<code><md-list flex ng-repeat="column in [1,2,3]">
    <md-list-item ng-click="log(button.url)" ng-repeat="button in insideDivided.next().value">
        {{log(button)}}
        {{button.title}}
    </md-list-item>
</md-list>
</code>```

Instruction {{log(button)}} write correct items to console

```<code>Object {title: "someTitle1", url: "/inside/fake.html", $$hashKey: "object:13"} root.js:100
Object {title: "someTitle2", url: "/inside/fake.html", $$hashKey: "object:14"} root.js:100
Object {title: "someTitle3", url: "/inside/fake.html", $$hashKey: "object:15"}
....
</code>```

But only creating empty <md-list>

```<code>    <!-- ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

        <!-- ngRepeat: button in insideDivided.next().value -->
    </md-list><!-- end ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

        <!-- ngRepeat: button in insideDivided.next().value -->
    </md-list><!-- end ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

        <!-- ngRepeat: button in insideDivided.next().value -->
    </md-list><!-- end ngRepeat: column in [1,2,3] -->
</code>```

Why ng-repeat work, but don't create md-list-items?

答:
ng-repeat isn't aware of generators. You need to convert it to an array first and iterate over that.

Here is the issue on github. https://github.com/angular/angular.js/issues/15202

It looks like they won't be supported anytime soon either.

ContentLicense: CC BY-SA 4.0

Body:
Generator:

$scope.inside = [...];

var generator        = function*() {
    var l = Math.ceil($scope.inside.length / 3);
    for (var i = 0; i < 3; i++) {
        yield $scope.inside.slice(l * i, l * (i + 1));
    }
};
$scope.insideDivided = generator();

Template:

<md-list flex ng-repeat="column in [1,2,3]">
    <md-list-item ng-click="log(button.url)" ng-repeat="button in insideDivided.next().value">
        {{log(button)}}
        {{button.title}}
    </md-list-item>
</md-list>

Instruction {{log(button)}} write correct items to console

Object {title: "someTitle1", url: "/inside/fake.html", $$hashKey: "object:13"} root.js:100
Object {title: "someTitle2", url: "/inside/fake.html", $$hashKey: "object:14"} root.js:100
Object {title: "someTitle3", url: "/inside/fake.html", $$hashKey: "object:15"}
....

But only creating empty <md-list>

    <md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

    </md-list><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

    </md-list><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">

    </md-list>

Why ng-repeat work, but don't create md-list-items?


问:
Workaround for lack of look-behind for Javascript regex
I have a working Python regex statement as:

```<code>regex = re.compile(r"(?<=(==))(.*)(?=(==))")
myList = regex.findall(contents)
</code>```

For context, the input string may resemble (for example):

```<code>== Test User ==
Comment here

== Test User 2 ==
Comment here
</code>```

And I wish to extract the username, and the related comment on the line below.

I want to use this regex in my Javascript program, however Javascript lacks look-behind functionality.

Is there a suitable workaround for this?

答:
The standard way is to match both the lookbehind and the desired data and use capturing groups to do what you want :

if it is to retrieve the data, then put it in a capturing group you will consult after each match

if it is to transform the data, you will want to have at least the "lookbehind" in a capturing group so you can reproduce it in the output, and maybe the desired data if you need to refer to it.

Examples :

```<code># in these examples, we look for "overflow" preceded by "stack"
"stackoverflow".match(/stack(.*)/)[1]                // -> overflow
"stackoverflow".replace(/(stack).*/, "$1underflow")  // -> stackunderflow
"stackoverflow".replace(/(stack)(.*)/,"$2ed $1")     // -> overflowed stack
</code>```

Another problem that we encounter with JavaScript's regex implementation is that String.prototype.match's behaviour is inconsistent : it will generally return an object akin to an array of captured groups, however if your regex specifies the global flag it will instead return an array of (string) matches, and the details of the capturing groups will be lost.

To work around this, you can use the Pattern.prototype.exec method instead :

var pattern = /==\s*([^=]+)/g;
var input = `== Test User ==
Comment here

== Test User 2 ==
Comment here`;
while (match = pattern.exec(input)) {
    console.log(match[1]);
}
```

Body:
I have a working Python regex statement as:

regex = re.compile(r"(?<=(==))(.*)(?=(==))")
myList = regex.findall(contents)

For context, the input string may resemble (for example):

== Test User ==
Comment here

== Test User 2 ==
Comment here

And I wish to extract the username, and the related comment on the line below.

I want to use this regex in my Javascript program, however Javascript lacks look-behind functionality.

Is there a suitable workaround for this?

Body:
The standard way is to match both the lookbehind and the desired data and use capturing groups to do what you want :

if it is to retrieve the data, then put it in a capturing group you will consult after each match

if it is to transform the data, you will want to have at least the "lookbehind" in a capturing group so you can reproduce it in the output, and maybe the desired data if you need to refer to it.

Examples :

# in these examples, we look for "overflow" preceded by "stack"
"stackoverflow".match(/stack(.*)/)[1]                // -> overflow
"stackoverflow".replace(/(stack).*/, "$1underflow")  // -> stackunderflow
"stackoverflow".replace(/(stack)(.*)/,"$2ed $1")     // -> overflowed stack

Another problem that we encounter with JavaScript's regex implementation is that String.prototype.match's behaviour is inconsistent : it will generally return an object akin to an array of captured groups, however if your regex specifies the global flag it will instead return an array of (string) matches, and the details of the capturing groups will be lost.

To work around this, you can use the Pattern.prototype.exec method instead :

var pattern = /==\s*([^=]+)/g;
var input = `== Test User ==
Comment here

== Test User 2 ==
Comment here`;
while (match = pattern.exec(input)) {
    console.log(match[1]);
}


问:
How write automaticaly the name of the day in the name of a table?
I would like to know how to automatically write the name of the current  day in the table name when i execute a request like :

from qgpltemp.monday  (if i run on monday)

from qgpltemp.tuesday (if i run on tuesday)

etc...

(the table is already created with the good name before executing the request)

I have Tried :

```<code>select DAYNAME(CURRENT_DATE)as day,cast (row1 as integer) from qgpltemp.:day
</code>```

and some other things , but i often get the error :

```<code>Error: [SQL0104] Elément syntaxique : n'est pas correct. Eléments possibles : <IDENTIFIER>.
SQLState:  42601
ErrorCode: -104
</code>```

The command DAYNAME(CURRENT_DATE)as day works fine, i only get the name of the day if i manually write .monday etc...

答:
Create an alias for the current day.  Then your procedures can just point to the alias.</p>

```<code>CREATE or replace ALIAS Qgpltemp.today FOR QGPLTEMP.MONDAY ;

select * from qqgpltemp.today;
</code>```

Body:
I would like to know how to automatically write the name of the current  day in the table name when i execute a request like :

from qgpltemp.monday  (if i run on monday)

from qgpltemp.tuesday (if i run on tuesday)

etc...

(the table is already created with the good name before executing the request)

I have Tried :

select DAYNAME(CURRENT_DATE)as day,cast (row1 as integer) from qgpltemp.:day

and some other things , but i often get the error :

Error: [SQL0104] Elément syntaxique : n'est pas correct. Eléments possibles : <IDENTIFIER>.
SQLState:  42601
ErrorCode: -104

The command DAYNAME(CURRENT_DATE)as day works fine, i only get the name of the day if i manually write .monday etc...

Body:
Create an alias for the current day.  Then your procedures can just point to the alias.

CREATE or replace ALIAS Qgpltemp.today FOR QGPLTEMP.MONDAY ;

select * from qqgpltemp.today;


问:
Deserializing JSON and saving the object to MySQL database
I am trying to save an object from POST request to my service. The request is sending a JSON:

```<code>{
"FirstName": "Ronnsie",
"LastName": "Wesleeyson",
"BirthPlace": "Zagreb",
"Gender": "M",
"OIB": "12345678901",
"CurrentPlace": "Mauritius",
"Department": "D_21510"
}
</code>```

and the error I am getting is as follows:

```<code>{
"Message": "An error has occurred.",
"ExceptionMessage": "Error executing the command 'INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) VALUES (, , , Mauritius, 1, 21510, )'. The error is 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , Mauritius, 1, 21510, )' at line 1'." ...}
</code>```

Now the request hits the controller here:

```<code>    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }
</code>```

and the SaveEmployee function is as follows:

```<code>    public long SaveEmployee(Employee employee)
    {
        string sqlString = String.Format(
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            employee.FirstName,
            employee.LastName,
            employee.BirthPlace,
            employee.CurrentPlace,
            employee.Gender == EmployeeGender.M ? 1 : 0,
            employee.Department.GetStringValue(),
            employee.OIB
        );

        MySqlCommand cmd = ExecuteSqlCommand(sqlString);
        return cmd.LastInsertedId;
    }

    MySqlCommand ExecuteSqlCommand(string sqlString)
    {
        try
        {
            // execute the SQL command
            MySqlCommand cmd = new MySqlCommand(sqlString, conn);
            cmd.ExecuteNonQuery();

            return cmd;
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                             sqlString, e.Message));
        }
    }
</code>```

I can't seem to find any error in the SQL syntax. However, it might be that there is a problem deserializing enums, so here they are:

DepartmentCode.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum DepartmentCode
    {
        D_21510,
        D_21520,
        D_21540,
        D_21570,
        D_SLFIN,
        D_SLKPO
    }

```<code>public static class DepartmentCodeExtensions
{
    const string S_21510 = "21510";
    const string S_21520 = "21520";
    const string S_21540 = "21540";
    const string S_21570 = "21570";
    const string S_SLFIN = "SLFIN";
    const string S_SLKPO = "SLKPO";

    public static string GetStringValue(this DepartmentCode dep)
    {
        switch (dep)
        {
            case DepartmentCode.D_21510:
                return S_21510;

            case DepartmentCode.D_21520:
                return S_21520;

            case DepartmentCode.D_21540:
                return S_21540;

            case DepartmentCode.D_21570:
                return S_21570;

            case DepartmentCode.D_SLFIN:
                return S_SLFIN;

            case DepartmentCode.D_SLKPO:
                return S_SLKPO;

            default:
                throw new ArgumentException("Given department code not supported.");
        }
    }
</code>```

EmployeeGender.cs

```<code>[JsonConverter(typeof(StringEnumConverter))]
    public enum EmployeeGender
    {
        M,
        F
    }
</code>```

Any ideas on what's the error here?

答:
You shouldn't use string.Format to put parameters into an SQL statement like that.  In addition to the bug you are seeing, it also leaves you wide open to SQL injection as @SLaks has mentioned.

Using command parameters will solve your problem and the SQL Injection vulnerability at the same time.

Body:
I am trying to save an object from POST request to my service. The request is sending a JSON:

{
"FirstName": "Ronnsie",
"LastName": "Wesleeyson",
"BirthPlace": "Zagreb",
"Gender": "M",
"OIB": "12345678901",
"CurrentPlace": "Mauritius",
"Department": "D_21510"
}

and the error I am getting is as follows:

{
"Message": "An error has occurred.",
"ExceptionMessage": "Error executing the command 'INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) VALUES (, , , Mauritius, 1, 21510, )'. The error is 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , Mauritius, 1, 21510, )' at line 1'." ...}

Now the request hits the controller here:

    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

and the SaveEmployee function is as follows:

    public long SaveEmployee(Employee employee)
    {
        string sqlString = String.Format(
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            employee.FirstName,
            employee.LastName,
            employee.BirthPlace,
            employee.CurrentPlace,
            employee.Gender == EmployeeGender.M ? 1 : 0,
            employee.Department.GetStringValue(),
            employee.OIB
        );

        MySqlCommand cmd = ExecuteSqlCommand(sqlString);
        return cmd.LastInsertedId;
    }

    MySqlCommand ExecuteSqlCommand(string sqlString)
    {
        try
        {
            // execute the SQL command
            MySqlCommand cmd = new MySqlCommand(sqlString, conn);
            cmd.ExecuteNonQuery();

            return cmd;
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                             sqlString, e.Message));
        }
    }

I can't seem to find any error in the SQL syntax. However, it might be that there is a problem deserializing enums, so here they are:

DepartmentCode.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum DepartmentCode
    {
        D_21510,
        D_21520,
        D_21540,
        D_21570,
        D_SLFIN,
        D_SLKPO
    }

public static class DepartmentCodeExtensions
{
    const string S_21510 = "21510";
    const string S_21520 = "21520";
    const string S_21540 = "21540";
    const string S_21570 = "21570";
    const string S_SLFIN = "SLFIN";
    const string S_SLKPO = "SLKPO";

    public static string GetStringValue(this DepartmentCode dep)
    {
        switch (dep)
        {
            case DepartmentCode.D_21510:
                return S_21510;

            case DepartmentCode.D_21520:
                return S_21520;

            case DepartmentCode.D_21540:
                return S_21540;

            case DepartmentCode.D_21570:
                return S_21570;

            case DepartmentCode.D_SLFIN:
                return S_SLFIN;

            case DepartmentCode.D_SLKPO:
                return S_SLKPO;

            default:
                throw new ArgumentException("Given department code not supported.");
        }
    }

EmployeeGender.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum EmployeeGender
    {
        M,
        F
    }

Any ideas on what's the error here?


问:
Spring MVC home page
I have HomeController class:

```<code>@Controller
public class HomeController {

    @RequestMapping("/")
    public String showPage() {
        return "main-menu";
    }
}
</code>```

My project structure:

Spring version: 4.3.9
web.xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

dispatcher-servlet.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
</code>```

It always shows index.jsp, never main-menu.jsp
I want a main-menu my Home Page. What should i do?

答:
The problem lies in your web.xml file:

```<code><servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.form</url-pattern>
</servlet-mapping>
</code>```

You declare to the servlet container that SpringMVC DispatcherServlet will only process URL ending in .form. So the request for home never reaches SpringMVC machinery - BTW, that also explains why divine's proposal of /welcome does not work either, but /welcome.form should...

You could also have a look to this other post from mine for a general discussion of how to process the root URL with SpringMVC.

Title: Spring MVC home page

Body:
I have HomeController class:

@Controller
public class HomeController {

    @RequestMapping("/")
    public String showPage() {
        return "main-menu";
    }
}

My project structure:

Spring version: 4.3.9
web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>

dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

It always shows index.jsp, never main-menu.jsp
I want a main-menu my Home Page. What should i do?

Body:
The problem lies in your web.xml file:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.form</url-pattern>
</servlet-mapping>

You declare to the servlet container that SpringMVC DispatcherServlet will only process URL ending in .form. So the request for home never reaches SpringMVC machinery - BTW, that also explains why divine's proposal of /welcome does not work either, but /welcome.form should...

You could also have a look to this other post from mine for a general discussion of how to process the root URL with SpringMVC.


问:
Oracle - exchange partitions with a table
I try to create a table2 on Oracle 11g.2.0.3 with:

```<code>CREATE table2
LOGGING TABLESPACE TS_table1_2014 PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS UNLIMITED BUFFER_POOL DEFAULT ) NOCOMPRESS
as (select * from table1 where date_text <= '2015-12-31');
</code>```

and I have received error below when I try to exchange this table2 with a partitioned table3:

```<code>alter table table3 exchange partition partition_name WITH TABLE table2;

    Error report -
    SQL Error: ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
    14097. 00000 -  "column type or size mismatch in ALTER TABLE EXCHANGE PARTITION"
    *Cause:    The corresponding columns in the tables specified in the
               ALTER TABLE EXCHANGE PARTITION are of different type or size
    *Action:   Ensure that the two tables have the same number of columns
               with the same type and size.
</code>```

I have test diferences with query below:

```<code>Select a.COLUMN_NAME
  , a.DATA_TYPE, b.DATA_TYPE
  , a.data_length, b.data_length
  , a.data_precision, b.data_precision
  , a.data_scale, b.data_scale
  , a.nullable, b.nullable
from ALL_TAB_COLUMNS a
full outer join ALL_TAB_COLUMNS b on a.column_name=b.column_name
 and b.owner=user and b.table_name='&table2'
 where  a.owner=user and a.table_name='&table1'
 and (
    nvl(a.data_type,'#')!=nvl(b.data_type,'#')
    or nvl(a.data_length,-1)!=nvl(b.data_length,-1)
    or nvl(a.data_precision,-100)!=nvl(b.data_precision,-100)
    or nvl(a.data_scale,-100)!=nvl(b.data_scale,-100)
    or nvl(a.nullable,'#')!=nvl(b.nullable,'#')
   )
;
</code>```

Some differences resulted are in a column size. This syntax "create as select" didn't keep order and size for new table created.

How can I create table2 as select from table1 with force keep same size columns as primary table1 source?

Thanks!

答:
I can't find any differences in your DDL.  What I suggest is to use the same DDL to create table2, then do:</p>

```<code>insert into table2 select * from table1;
</code>```

Body:
I try to create a table2 on Oracle 11g.2.0.3 with:

CREATE table2
LOGGING TABLESPACE TS_table1_2014 PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS UNLIMITED BUFFER_POOL DEFAULT ) NOCOMPRESS
as (select * from table1 where date_text <= '2015-12-31');

and I have received error below when I try to exchange this table2 with a partitioned table3:

alter table table3 exchange partition partition_name WITH TABLE table2;

    Error report -
    SQL Error: ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
    14097. 00000 -  "column type or size mismatch in ALTER TABLE EXCHANGE PARTITION"
    *Cause:    The corresponding columns in the tables specified in the
               ALTER TABLE EXCHANGE PARTITION are of different type or size
    *Action:   Ensure that the two tables have the same number of columns
               with the same type and size.

I have test diferences with query below:

Select a.COLUMN_NAME
  , a.DATA_TYPE, b.DATA_TYPE
  , a.data_length, b.data_length
  , a.data_precision, b.data_precision
  , a.data_scale, b.data_scale
  , a.nullable, b.nullable
from ALL_TAB_COLUMNS a
full outer join ALL_TAB_COLUMNS b on a.column_name=b.column_name
 and b.owner=user and b.table_name='&table2'
 where  a.owner=user and a.table_name='&table1'
 and (
    nvl(a.data_type,'#')!=nvl(b.data_type,'#')
    or nvl(a.data_length,-1)!=nvl(b.data_length,-1)
    or nvl(a.data_precision,-100)!=nvl(b.data_precision,-100)
    or nvl(a.data_scale,-100)!=nvl(b.data_scale,-100)
    or nvl(a.nullable,'#')!=nvl(b.nullable,'#')
   )
;

Some differences resulted are in a column size. This syntax "create as select" didn't keep order and size for new table created.

How can I create table2 as select from table1 with force keep same size columns as primary table1 source?

Thanks!

Body:
I can't find any differences in your DDL.  What I suggest is to use the same DDL to create table2, then do:

insert into table2 select * from table1;


答:
We created a class to store and retrieve objects in and out of a static dictionary of objects, it sits in our PCL, but could be used in Forms as it's generic compilable code.

Create the class:

```<code>public static class ApplicationState
{
    private static Dictionary<string, object> _values =
               new Dictionary<string, object>();

    /// <summary>
    /// Sets a value in the dictionary with the entered values.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public static void SetValue(string key, object value)
    {
        if (_values.ContainsKey(key))
        {
            _values.Remove(key);
        }
        _values.Add(key, value);
    }

    /// <summary>
    /// Gets the object with the associated entered key.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T GetValue<T>(string key)
    {
        if (_values.ContainsKey(key))
        {
            return (T)_values[key];
        }
        else
        {
            return default(T);
        }
    }

    /// <summary>
    /// Clears all values from the ApplicationState
    /// </summary>
    public static void ClearValues()
    {
        _values.Clear();
    }

    /// <summary>
    /// Checks if the dictionary contains a value with a key equal to the entered string
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static bool ContainsValue(string key)
    {
        if (_values.ContainsKey(key))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// Gets all values currently saved within the ApplicationState, in the form of a dictionary(string, object)
    /// </summary>
    /// <returns></returns>
    public static Dictionary<string, object> GetAllValues()
    {
        return _values;
    }

    /// <summary>
    /// Removes a KeyValuePair from the dictionary where the key equals the entered string
    /// </summary>
    /// <param name="key"></param>
    public static void Remove(string key)
    {
        _values.Remove(key);
    }

    /// <summary>
    /// Removes all KeyValuePairs from the dictionary where the key starts with entered string
    /// </summary>
    /// <param name="startsWith"></param>
    public static void RemoveStartsWith(string startsWith)
    {
        var toRemove = _values.Where(x => x.Key.StartsWith(startsWith))
                     .Select(pair => pair.Key)
                     .ToList();

        foreach (var key in toRemove)
        {
            _values.Remove(key);
        }
    }
}
</code>```

the data is then set by using the following:

```<code> ApplicationState.SetValue("MyKey", ObjectToStore);
</code>```

and to retrieve it you simply use:

```<code> ApplicationState.GetValue<ObjectToStore>("MyKey");
</code>```

Edit:

So you can pull the object/variable out of the dictionary, change it, add to it etc. then simply put it back in under the same key, you could do this on page change, button click, however you want. It's really quite simple and versatile.

Simple int and object example as requested

Storing an int:

```<code>int i = 10

ApplicationState.SetValue("ThisIsANumber", i);
</code>```

or

```<code>ApplicationState.SetValue("ThisIsANumber", 10);
</code>```

Retrieving an Int

```<code>int variable = ApplicationState.GetValue<int>("ThisIsANumber");
</code>```

Storing an Object

```<code>Object obj;

ApplicationState.SetValue("ThisIsAnObject", obj);
</code>```

Retrieve an Object

```<code>Object theObject = ApplicationState.GetValue<Object>("ThisIsAnObject");
</code>```

Title: Are there any performance or coding issues with passing an object to multiple pages as a way to share variables for tabbed pages?

Body:
I am using a tabbed page like this:

public partial class MainPage : TabbedPage
{

    public MainPage()
    {
        InitializeComponent();

        var phrasesPage = new NavigationPage(new PhrasesPage())
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }

I want to share variables between my pages. For example a score number that will show on all pages and a few other variables.

I would like to code my application so that it's easy to maintain.

public partial class MainPage : TabbedPage
{

   public class Person
   {
       public string Name { get; set; }
       public int Age { get; set; }
       public Person(){}
       public Person(string name, int age)
       {
           Name = name;
           Age = age;
       }
    }

    public MainPage()
    {
        InitializeComponent();

        var person = Person p=new Person()
        {
           Name = "Han Solo",
           Age = 39
        };

        var phrasesPage = new NavigationPage(new PhrasesPage(person))
        {
            Title = "Play",
            Icon = "play.png"
        };
        ....
        ....
        Children.Add(phrasesPage);
        Children.Add(categoriesPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }

Can someone advise me if it would be good to create an object that contains all the shared variables and then to pass that object to the constructor of each of the pages as a parameter when the pages are created with a "new"?

Body:
We created a class to store and retrieve objects in and out of a static dictionary of objects, it sits in our PCL, but could be used in Forms as it's generic compilable code.

Create the class:

public static class ApplicationState
{
    private static Dictionary<string, object> _values =
               new Dictionary<string, object>();

    /// <summary>
    /// Sets a value in the dictionary with the entered values.
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public static void SetValue(string key, object value)
    {
        if (_values.ContainsKey(key))
        {
            _values.Remove(key);
        }
        _values.Add(key, value);
    }

    /// <summary>
    /// Gets the object with the associated entered key.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T GetValue<T>(string key)
    {
        if (_values.ContainsKey(key))
        {
            return (T)_values[key];
        }
        else
        {
            return default(T);
        }
    }

    /// <summary>
    /// Clears all values from the ApplicationState
    /// </summary>
    public static void ClearValues()
    {
        _values.Clear();
    }

    /// <summary>
    /// Checks if the dictionary contains a value with a key equal to the entered string
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static bool ContainsValue(string key)
    {
        if (_values.ContainsKey(key))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// Gets all values currently saved within the ApplicationState, in the form of a dictionary(string, object)
    /// </summary>
    /// <returns></returns>
    public static Dictionary<string, object> GetAllValues()
    {
        return _values;
    }

    /// <summary>
    /// Removes a KeyValuePair from the dictionary where the key equals the entered string
    /// </summary>
    /// <param name="key"></param>
    public static void Remove(string key)
    {
        _values.Remove(key);
    }

    /// <summary>
    /// Removes all KeyValuePairs from the dictionary where the key starts with entered string
    /// </summary>
    /// <param name="startsWith"></param>
    public static void RemoveStartsWith(string startsWith)
    {
        var toRemove = _values.Where(x => x.Key.StartsWith(startsWith))
                     .Select(pair => pair.Key)
                     .ToList();

        foreach (var key in toRemove)
        {
            _values.Remove(key);
        }
    }
}

the data is then set by using the following:

 ApplicationState.SetValue("MyKey", ObjectToStore);

and to retrieve it you simply use:

 ApplicationState.GetValue<ObjectToStore>("MyKey");

Edit:

So you can pull the object/variable out of the dictionary, change it, add to it etc. then simply put it back in under the same key, you could do this on page change, button click, however you want. It's really quite simple and versatile.

Simple int and object example as requested

Storing an int:

int i = 10

ApplicationState.SetValue("ThisIsANumber", i);

or

ApplicationState.SetValue("ThisIsANumber", 10);

Retrieving an Int

int variable = ApplicationState.GetValue<int>("ThisIsANumber");

Storing an Object

Object obj;

ApplicationState.SetValue("ThisIsAnObject", obj);

Retrieve an Object

Object theObject = ApplicationState.GetValue<Object>("ThisIsAnObject");


问:
How to transform employee attendence from rows to columns
I have two tables, lets say, tblEmployees and tblAttendence. Employees table only contains employee codes and names, and attendence tables contains entry for each day for each employee if it is absent or not.

I post my test script with this question with 5 dummy records for employee and 30 rows in attendence table for each employee for a month (june 2017), so attendence table will have total 150(5x30) rows. I need the output in a tabular form showing employee names in each row but each day will appear in separate column. In my test script I did this for only 7 days with using left outer joins to same table with different day condition.

Here is the script:

```<code>----create dummy tables for 'Employee', and 'Attendence'
declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = '1 jun 2017'
declare @DateLast date = '30 jun 2017'

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = ('E00' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = ('Emp_Name_' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end

-------at this points, we have 2 tables,
-------tblEmployee contains 5 dummy records

----this query will do the actual job
----i.e, tranform attendence data against each employee for each day

select
e.*
,t1.Absence as Day1
,t2.Absence as Day2
,t3.Absence as Day3
,t4.Absence as Day4
,t5.Absence as Day5
,t6.Absence as Day6
,t7.Absence as Day7

from @tblEmployee e
left outer join @tblAttendence t1 on t1.EmployeeID = e.EmployeeID and t1.AttendenceDay = 1
left outer join @tblAttendence t2 on t2.EmployeeID = e.EmployeeID and t2.AttendenceDay = 2
left outer join @tblAttendence t3 on t3.EmployeeID = e.EmployeeID and t3.AttendenceDay = 3
left outer join @tblAttendence t4 on t4.EmployeeID = e.EmployeeID and t4.AttendenceDay = 4
left outer join @tblAttendence t5 on t5.EmployeeID = e.EmployeeID and t5.AttendenceDay = 5
left outer join @tblAttendence t6 on t6.EmployeeID = e.EmployeeID and t6.AttendenceDay = 6
left outer join @tblAttendence t7 on t7.EmployeeID = e.EmployeeID and t7.AttendenceDay = 7
</code>```

Now I have to do same work with full month days, means 30 columns required against employee record and using this technique I have to copy paste same code.

Is it a right approach for solving this problem or is there any better solution?

答:
While you can repeat the table joins multiple times, using pivoting technique as below can get the desired output for 30/31 days of the month

Hope it helps

```<code>select e.*,dc.*
from @tblEmployee e
left join (select EmployeeID,[1] as Day1, [2] as Day2, [3] as Day3, [4] as
Day4, [5] as Day5,
                         [6] as Day6, [7] as Day7, [8] as Day8, [9] as Day9, [10] as Day10,
                         [11] as Day11, [12] as Day12, [13] as Day13, [14] as Day14, [15] as Day15,
                         [16] as Day16, [17] as Day17, [18] as Day18, [19] as Day19, [20] as Day20,
                         [21] as Day21,[22] as Day22,[23] as Day23,[24] as Day24,[25] as Day25,[26] as Day26,
                         [27] as Day27,[28] as Day28,[29] as Day29,[30] as Day30,[31] as Day31
                from (select EmployeeID,Absence,AttendenceDay
                      from   @tblAttendence) d
                      pivot (max(Absence)
                              for AttendenceDay  in ([1], [2], [3], [4], [5],
                                                    [6], [7], [8], [9], [10],
                                                    [11], [12], [13], [14], [15],
                                                    [16], [17], [18], [19], [20],
                                                    [21], [22], [23], [24], [25],
                                                    [26], [27], [28], [29], [30],[31])) as pvt) as dc
 on dc.EmployeeId = e.EmployeeId
</code>```

Body:
I have two tables, lets say, tblEmployees and tblAttendence. Employees table only contains employee codes and names, and attendence tables contains entry for each day for each employee if it is absent or not.

I post my test script with this question with 5 dummy records for employee and 30 rows in attendence table for each employee for a month (june 2017), so attendence table will have total 150(5x30) rows. I need the output in a tabular form showing employee names in each row but each day will appear in separate column. In my test script I did this for only 7 days with using left outer joins to same table with different day condition.

Here is the script:

----create dummy tables for 'Employee', and 'Attendence'
declare @tblEmployee table(
EmployeeID int,
EmployeeCode varchar(10),
EmployeeName varchar(255)
)

declare @tblAttendence table(
AttendenceID int identity(1, 1),
EmployeeID int,

AttendenceDate date,
AttendenceDay int,

Absence int
)

-----insert dummy records in both tables
declare @EmployeeID int = 1
declare @EmployeeCode varchar(10)
declare @EmployeeName varchar(255)

declare @CountEmployee int = 1
declare @CountDays int = 1

declare @UserYear int = 2017
declare @UserMonth int = 5

declare @DateFirst date = '1 jun 2017'
declare @DateLast date = '30 jun 2017'

declare @DateCurrent date = @DateFirst

while @CountEmployee <= 5
begin

    set @EmployeeID = @CountEmployee
    set @EmployeeCode = ('E00' + CAST(@CountEmployee as varchar(10)))
    set @EmployeeName = ('Emp_Name_' + CAST(@CountEmployee as varchar(10)))

    insert into @tblEmployee(
        EmployeeCode ,
        EmployeeID ,
        EmployeeName
        )

    select
        @EmployeeCode as EmployeeCode ,
        @EmployeeID  as EmployeeID ,
        @EmployeeName as EmployeeName;

    set @DateCurrent = @DateFirst
    set @CountDays = 1

    while @DateCurrent <= @DateLast
    begin

        insert into @tblAttendence(
            EmployeeID ,

            AttendenceDate ,
            AttendenceDay,
            Absence
            )

            select
            @EmployeeID  as EmployeeID ,

            @DateCurrent as AttendenceDate ,
            day(@DateCurrent) as AttendenceDay,
            CAST(ROUND(RAND(),0) AS BIT) as Absence

            set @DateCurrent = DATEADD(day, @CountDays, @DateFirst)
            set @CountDays = @CountDays + 1

    end

    set @CountEmployee = @CountEmployee + 1

end

-------at this points, we have 2 tables,
-------tblEmployee contains 5 dummy records

----this query will do the actual job
----i.e, tranform attendence data against each employee for each day

select
e.*
,t1.Absence as Day1
,t2.Absence as Day2
,t3.Absence as Day3
,t4.Absence as Day4
,t5.Absence as Day5
,t6.Absence as Day6
,t7.Absence as Day7

from @tblEmployee e
left outer join @tblAttendence t1 on t1.EmployeeID = e.EmployeeID and t1.AttendenceDay = 1
left outer join @tblAttendence t2 on t2.EmployeeID = e.EmployeeID and t2.AttendenceDay = 2
left outer join @tblAttendence t3 on t3.EmployeeID = e.EmployeeID and t3.AttendenceDay = 3
left outer join @tblAttendence t4 on t4.EmployeeID = e.EmployeeID and t4.AttendenceDay = 4
left outer join @tblAttendence t5 on t5.EmployeeID = e.EmployeeID and t5.AttendenceDay = 5
left outer join @tblAttendence t6 on t6.EmployeeID = e.EmployeeID and t6.AttendenceDay = 6
left outer join @tblAttendence t7 on t7.EmployeeID = e.EmployeeID and t7.AttendenceDay = 7

Now I have to do same work with full month days, means 30 columns required against employee record and using this technique I have to copy paste same code.

Is it a right approach for solving this problem or is there any better solution?

Body:
While you can repeat the table joins multiple times, using pivoting technique as below can get the desired output for 30/31 days of the month

Hope it helps

select e.*,dc.*
from @tblEmployee e
left join (select EmployeeID,[1] as Day1, [2] as Day2, [3] as Day3, [4] as
Day4, [5] as Day5,
                         [6] as Day6, [7] as Day7, [8] as Day8, [9] as Day9, [10] as Day10,
                         [11] as Day11, [12] as Day12, [13] as Day13, [14] as Day14, [15] as Day15,
                         [16] as Day16, [17] as Day17, [18] as Day18, [19] as Day19, [20] as Day20,
                         [21] as Day21,[22] as Day22,[23] as Day23,[24] as Day24,[25] as Day25,[26] as Day26,
                         [27] as Day27,[28] as Day28,[29] as Day29,[30] as Day30,[31] as Day31
                from (select EmployeeID,Absence,AttendenceDay
                      from   @tblAttendence) d
                      pivot (max(Absence)
                              for AttendenceDay  in ([1], [2], [3], [4], [5],
                                                    [6], [7], [8], [9], [10],
                                                    [11], [12], [13], [14], [15],
                                                    [16], [17], [18], [19], [20],
                                                    [21], [22], [23], [24], [25],
                                                    [26], [27], [28], [29], [30],[31])) as pvt) as dc
 on dc.EmployeeId = e.EmployeeId


问:
In my picker view array data is not loading?
In this I try to load picker view with data but not able to load data and it is showing as shown in below image that only empty picker view is displaying i was trying from a long time can any one help me what's wrong in implementing ?

```<code>    var firstName : String = ""
    var lastName : String = ""
    var mobileNumber : Int = 0
    var email : String = ""
    var defaultValue = 1
    let url = "http://www.json-generator.com/api/json/get/bPmyumGWeW?indent=2"
    var dateofbirth : String = ""
    var Gender : String = ""
    var genderArray = [String]()

        override func viewDidLoad() {
        super.viewDidLoad()
        let picker = UIPickerView()
        picker.isHidden = true
        picker.delegate = self
        DateofBirthTextfield.delegate = self
        selectGenderTextField.inputView = picker
        MyaccountJsonWithURL()
        genderArray = ["Male","Female"]

    }

    func MyaccountJsonWithURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                //  print(jsonObj!.value(forKey: "Detail"))
                if let profileArray = jsonObj!.value(forKey: "profile") as? NSArray {
                    for array in profileArray {
                        if let profileDict = array as? NSDictionary {
                            if let firstName = profileDict.value(forKey: "first name"){
                                self.firstName.append(firstName as! String)
                            }
                            if let lastName = profileDict.value(forKey: "last name"){
                                self.lastName.append(lastName as! String)
                            }
                            self.mobileNumber = profileDict.value(forKey: "mobile") as! Int
                            print(self.mobileNumber)
                            if let emailId = profileDict.value(forKey: "email"){
                                self.email.append(emailId as! String)
                            }
                            self.dateofbirth = profileDict.value(forKey: "dob") as! String
                            if let gender = profileDict.value(forKey: "gender"){
                                self.Gender.append(gender as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.FirstNameTextfield.text = self.firstName
                    self.LastNameTextfield.text = self.lastName
                    self.MobileNumberTextfield.text = String(describing: self.mobileNumber)
                    self.EmailIdTextfield.text = self.email
                    self.DateofBirthTextfield.text = String(describing: self.dateofbirth)
                    self.selectGenderTextField.text = self.Gender
                })
            }
        }).resume()
    }

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return genderArray.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return genderArray[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectGenderTextField.text = genderArray[row]
        self.view.endEditing(false)
    }
</code>```

答: In viewDidLoad you set picker as hidden. Set picker.isHidden = false to display it

Body:
In this I try to load picker view with data but not able to load data and it is showing as shown in below image that only empty picker view is displaying i was trying from a long time can any one help me what's wrong in implementing ?

    var firstName : String = ""
    var lastName : String = ""
    var mobileNumber : Int = 0
    var email : String = ""
    var defaultValue = 1
    let url = "http://www.json-generator.com/api/json/get/bPmyumGWeW?indent=2"
    var dateofbirth : String = ""
    var Gender : String = ""
    var genderArray = [String]()

        override func viewDidLoad() {
        super.viewDidLoad()
        let picker = UIPickerView()
        picker.isHidden = true
        picker.delegate = self
        DateofBirthTextfield.delegate = self
        selectGenderTextField.inputView = picker
        MyaccountJsonWithURL()
        genderArray = ["Male","Female"]

    }

    func MyaccountJsonWithURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                //  print(jsonObj!.value(forKey: "Detail"))
                if let profileArray = jsonObj!.value(forKey: "profile") as? NSArray {
                    for array in profileArray {
                        if let profileDict = array as? NSDictionary {
                            if let firstName = profileDict.value(forKey: "first name"){
                                self.firstName.append(firstName as! String)
                            }
                            if let lastName = profileDict.value(forKey: "last name"){
                                self.lastName.append(lastName as! String)
                            }
                            self.mobileNumber = profileDict.value(forKey: "mobile") as! Int
                            print(self.mobileNumber)
                            if let emailId = profileDict.value(forKey: "email"){
                                self.email.append(emailId as! String)
                            }
                            self.dateofbirth = profileDict.value(forKey: "dob") as! String
                            if let gender = profileDict.value(forKey: "gender"){
                                self.Gender.append(gender as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.FirstNameTextfield.text = self.firstName
                    self.LastNameTextfield.text = self.lastName
                    self.MobileNumberTextfield.text = String(describing: self.mobileNumber)
                    self.EmailIdTextfield.text = self.email
                    self.DateofBirthTextfield.text = String(describing: self.dateofbirth)
                    self.selectGenderTextField.text = self.Gender
                })
            }
        }).resume()
    }

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return genderArray.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return genderArray[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectGenderTextField.text = genderArray[row]
        self.view.endEditing(false)
    }


问:
How to make a movie out of images in python
I currently try to make a movie out of images, but i could not find anything helpful .

Here is my code so far:

```<code>import time

from PIL import  ImageGrab

x =0

while True:
    try:
        x+= 1
        ImageGrab().grab().save('img{}.png'.format(str(x))
    except:
        movie = #Idontknow
        for _ in range(x):
            movie.save("img{}.png".format(str(_)))

movie.save()
</code>```

答:
Thanks  , but i found an alternative solution using ffmpeg:

```<code>def save():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
</code>```

But thank you for your help :)

Body:
I currently try to make a movie out of images, but i could not find anything helpful .

Here is my code so far:

import time

from PIL import  ImageGrab

x =0

while True:
    try:
        x+= 1
        ImageGrab().grab().save('img{}.png'.format(str(x))
    except:
        movie = #Idontknow
        for _ in range(x):
            movie.save("img{}.png".format(str(_)))

movie.save()

Body:
Thanks  , but i found an alternative solution using ffmpeg:

def save():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")

But thank you for your help :)


问:
How many databases per instance in JanusGraph? How is security configured between databases?
I am looking for information about databases per instance in JanusGraph and couldn't find proper documentation for it. The main concern in the security boundary between the databases in one instance. Let's say there are 2 databases in one instance of JanusGraph. Is it possible to configure security such that user A only has access to Database1 and user B only has access to Database2? If so, how is this security handled. </p>

答:
In JanusGraph as it exists today, a "database" would be a separate Graph, each of which must be defined and instantiated at server start. JanusGraph adheres to the TinkerPop specifications, so it is run with the Gremlin server, which comes with its own authenticators: http://tinkerpop.apache.org/docs/current/reference/#_security_and_execution.

The out of the box authenticators only authenticate for server level access. However, with this PR being merged into TinkerPop: https://github.com/apache/tinkerpop/pull/583, you can write a custom authentication scheme that takes into account graph level access.

Also note that this PR: https://github.com/JanusGraph/janusgraph/pull/392 is currently open in the JanusGraph repo which will allow for the instantiation/creation of graphs, i.e. "databases", dynamically (post server start). Take a look at the GraphManager class there if you end up implementing a custom authentication scheme that takes into account graph level access, and if you do, you should commit your changes upstream into OSS.


问:
Laravel mysql query shut down server
I'm currently building an application with Laravel php Framework using Eloquent ORM. Im just trying to optimize this query because it takes very long time to display results.

Here's the code, How can i optimze it?

```<code>$messages = DB::table('mp as m1')
            ->select(DB::raw('m1.id as id, m1.user_id, m1.titre, m1.titremd5, content, m1.vu, users.name, users.slug, users.avatar, m1.horodateur, m1.id_conversation'))
            ->join('users', 'm1.user_id', '=', 'users.id')
            ->whereRaw('id_conversation IN (SELECT id FROM conversations_in WHERE user_id = '.Auth::user()->id.' AND visible=1 AND horodateur_fin = "") AND m1.id = (SELECT MAX(mp.id) FROM mp WHERE mp.id_conversation = m1.id_conversation)')
            ->orderBy('m1.id', 'DESC')
            ->paginate(10);
</code>```

I have no idea why this work so slow and it takes like 10 seconds to load page. Can somebody help me out?

答: Add db indexes for columns: horodateur_fin, visible</p>

Title: Laravel mysql query shut down server

Body:
I'm currently building an application with Laravel php Framework using Eloquent ORM. Im just trying to optimize this query because it takes very long time to display results.

Here's the code, How can i optimze it?

$messages = DB::table('mp as m1')
            ->select(DB::raw('m1.id as id, m1.user_id, m1.titre, m1.titremd5, content, m1.vu, users.name, users.slug, users.avatar, m1.horodateur, m1.id_conversation'))
            ->join('users', 'm1.user_id', '=', 'users.id')
            ->whereRaw('id_conversation IN (SELECT id FROM conversations_in WHERE user_id = '.Auth::user()->id.' AND visible=1 AND horodateur_fin = "") AND m1.id = (SELECT MAX(mp.id) FROM mp WHERE mp.id_conversation = m1.id_conversation)')
            ->orderBy('m1.id', 'DESC')
            ->paginate(10);

I have no idea why this work so slow and it takes like 10 seconds to load page. Can somebody help me out?


问:
How to get details of all the child at same time in single list view from real-time database firebase
i am able to retrieve details of a single child on the list view but not all the child from firebase database. I want to access the child directly.

Here is my code

database pic

emulator pic

```<code> public class ViewDatabase extends AppCompatActivity {
 private static final String TAG = "ViewDatabase";
 private DatabaseReference databaseReference;
 private ListView mListView;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.view_database_layout);
 mListView = (ListView) findViewById(R.id.listview);
   databaseReference =
 FirebaseDatabase.getInstance().getReference().child("hello");
 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

  }
 private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

        userinfo user = snapshot.getValue(userinfo.class);

        Log.d(TAG, "showData: name: " + user.getName());
        Log.d(TAG, "showData: Mobile: " + user.getMob());
        Log.d(TAG, "showData: Vehicle: " + user.getVehicle());
        Log.d(TAG, "showData: Address: " + user.getaddress());

        ArrayList<String> array = new ArrayList<>();
        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
        ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

   }
 }
</code>```

答:
The problem is that you're creating a new array and adapter for every item in the snapshot. You should only create the array only once, add all items to it, and then create an adapter from the array:

```<code>private void showData(DataSnapshot dataSnapshot) {
    ArrayList<String> array = new ArrayList<>();
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        userinfo user = snapshot.getValue(userinfo.class);

        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
    }
    ArrayAdapter adapter = new ArrayAdapter(this,
 android.R.layout.simple_list_item_1, array);
    mListView.setAdapter(adapter);
   }
 }
</code>```

With this you'll end up with 4 items in the list view for each child node in the database. While this technically works, it's probably not what you want. A more common representation would be to add a single item to the array for every user:

```<code>private void showData(DataSnapshot dataSnapshot) {
    ArrayList<String> array = new ArrayList<>();
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        userinfo user = snapshot.getValue(userinfo.class);

        array.add(user.getName()+" ("+user.getMob()+")\n"+user.getVehicle()+"\n"user.getaddress());
    }
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
    mListView.setAdapter(adapter);
   }
 }
</code>```

I also recommend looking into FirebaseUI, which has a FirebaseListAdapter and other classes that take away the need for creating your own adapter for common cases.

Body:
i am able to retrieve details of a single child on the list view but not all the child from firebase database. I want to access the child directly.

Here is my code

database pic

emulator pic

 public class ViewDatabase extends AppCompatActivity {
 private static final String TAG = "ViewDatabase";
 private DatabaseReference databaseReference;
 private ListView mListView;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.view_database_layout);
 mListView = (ListView) findViewById(R.id.listview);
   databaseReference =
 FirebaseDatabase.getInstance().getReference().child("hello");
 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

  }
 private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

        userinfo user = snapshot.getValue(userinfo.class);

        Log.d(TAG, "showData: name: " + user.getName());
        Log.d(TAG, "showData: Mobile: " + user.getMob());
        Log.d(TAG, "showData: Vehicle: " + user.getVehicle());
        Log.d(TAG, "showData: Address: " + user.getaddress());

        ArrayList<String> array = new ArrayList<>();
        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
        ArrayAdapter adapter = new ArrayAdapter(this,
    android.R.layout.simple_list_item_1, array);
        mListView.setAdapter(adapter);
    }

   }
 }

Body:
The problem is that you're creating a new array and adapter for every item in the snapshot. You should only create the array only once, add all items to it, and then create an adapter from the array:

private void showData(DataSnapshot dataSnapshot) {
    ArrayList<String> array = new ArrayList<>();
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        userinfo user = snapshot.getValue(userinfo.class);

        array.add(user.getName());
        array.add(user.getMob());
        array.add(user.getVehicle());
        array.add(user.getaddress());
    }
    ArrayAdapter adapter = new ArrayAdapter(this,
 android.R.layout.simple_list_item_1, array);
    mListView.setAdapter(adapter);
   }
 }

With this you'll end up with 4 items in the list view for each child node in the database. While this technically works, it's probably not what you want. A more common representation would be to add a single item to the array for every user:

private void showData(DataSnapshot dataSnapshot) {
    ArrayList<String> array = new ArrayList<>();
    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        userinfo user = snapshot.getValue(userinfo.class);

        array.add(user.getName()+" ("+user.getMob()+")\n"+user.getVehicle()+"\n"user.getaddress());
    }
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
    mListView.setAdapter(adapter);
   }
 }

I also recommend looking into FirebaseUI, which has a FirebaseListAdapter and other classes that take away the need for creating your own adapter for common cases.


问:
Return closest attribute from radio button with JQuery on click
I have two radio buttons, I want to use JS / JQuery to extract the data-product-name from whichever is clicked (before any form submission).

I am trying this sort of code but can't get it working:

```<code>    return jQuery({{Click Element}}).closest("form").attr('[data-product-name]');
</code>```

For context, this is to use in Google Tag Manager custom JavaScript variable to put the data in some tracking.

Radio button code:

```<code>    <div class="choose-variants">
    <input type="radio"
    id="MB0"
    name="variantSku"
    value="MB"
    data-unit-price="9"
    data-product-name="HB MB" checked />
<label for="MB0">B & C
<span>Save<strong class="choose-label">Recommended</strong></span>
</label>
<input type="radio"
    id="MB-O1"
    name="variantSku"
    value="MB-O"
    data-unit-price="9"data-product-name="HB MB O"/>
<label for="MB-O1">B only
</label>
</code>```

答:
Here is the working example for you. Click on the radio buttons and you will get your output in console:

$('input[type=radio]').change(function() {
  console.log($(this).data('product-name'))
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choose-variants">
  <input type="radio" id="MB0" name="variantSku" value="MB" data-unit-price="9" data-product-name="HB MB" checked />
  <label for="MB0">B & C
<span>Save<strong class="choose-label">Recommended</strong></span>
</label>
  <input type="radio" id="MB-O1" name="variantSku" value="MB-O" data-unit-price="9" data-product-name="HB MB O" />
  <label for="MB-O1">B only
</label></code>```

Body:
I have two radio buttons, I want to use JS / JQuery to extract the data-product-name from whichever is clicked (before any form submission).

I am trying this sort of code but can't get it working:

    return jQuery({{Click Element}}).closest("form").attr('[data-product-name]');

For context, this is to use in Google Tag Manager custom JavaScript variable to put the data in some tracking.

Radio button code:

    <input type="radio"
    id="MB0"
    name="variantSku"
    value="MB"
    data-unit-price="9"
    data-product-name="HB MB" checked />
B & C
SaveRecommended

<input type="radio"
    id="MB-O1"
    name="variantSku"
    value="MB-O"
    data-unit-price="9"data-product-name="HB MB O"/>
B only

Body:
Here is the working example for you. Click on the radio buttons and you will get your output in console:

$('input[type=radio]').change(function() {
  console.log($(this).data('product-name'))
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choose-variants">
  <input type="radio" id="MB0" name="variantSku" value="MB" data-unit-price="9" data-product-name="HB MB" checked />
  <label for="MB0">B &amp; C
<span>Save<strong class="choose-label">Recommended</strong></span>
</label>
  <input type="radio" id="MB-O1" name="variantSku" value="MB-O" data-unit-price="9" data-product-name="HB MB O" />
  <label for="MB-O1">B only
</label>