问:
Java Beginner: How do I link one linked list to another?
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

```<code> List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);
</code>```

OUTPUT:

```<code> [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]
</code>```

答:
addAll() just takes the values from the second linked list.  Changes to the indexes and set values in the second list will not affect the first.  (Note: changes to the objects themselves will stay because they both point to the same object).

You can make a List of Lists if that is what you are looking for.

Body:
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

 List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);

OUTPUT:

 [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]


来源: stackexchange

问:
How to insert data into elasticsearch
I am new to Elasticearch, and I have been trying for 2 days to insert some data into Elasticearch.
I found on Google that there are many pages to help to create an index (I am not clear about "index", does it mean "insert" in other terms?)
Then many places give some curl command, and I really don't know where to execute these code lines to insert data. Example:

```<code>curl -XPOST "http://[localhost]:9200/indexname/typename/optionalUniqueId" -d '{ "field" : "value" }'
</code>```

I am using Window 7 and I have installed Java and run elasticsearch successfully.
Could anybody show me more details about how to insert data into Elasticearch

Many thanks

答:
To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run

```<code>Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'
</code>```

Note the Index name MUST be in lowercase.

ContentLicense: CC BY-SA 4.0

Title: How to insert data into elasticsearch

Body:
I am new to Elasticearch, and I have been trying for 2 days to insert some data into Elasticearch.
I found on Google that there are many pages to help to create an index (I am not clear about "index", does it mean "insert" in other terms?)
Then many places give some curl command, and I really don't know where to execute these code lines to insert data. Example:

curl -XPOST "http://[localhost]:9200/indexname/typename/optionalUniqueId" -d '{ "field" : "value" }'

I am using Window 7 and I have installed Java and run elasticsearch successfully.
Could anybody show me more details about how to insert data into Elasticearch

Many thanks

Body:
To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run

Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'

Note the Index name MUST be in lowercase.

ContentLicense: CC BY-SA 3.0


问:
Finding strict prefixes in lucene
I'm trying to implement an autocomplete feature with Lucene. For example, if the user types "Lucene", the returned results may be "Lucene in Action" and "Lucene for Dummies".

The problem I'm having is that the field should start with with the searched text, it shouldn't be somewhere in the middle; searching for "Lucene" shouldn't return "Enterprise Lucene". Here's my code so far, which doesn't exclude the above:

```<code>    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);

    IndexWriter indexWriter = new IndexWriter(index, config);
    addDocument(indexWriter, "Luceneinaction");
    addDocument(indexWriter, "LuceneforDummies");
    addDocument(indexWriter, "WhyisLucenesohard");
    addDocument(indexWriter, "Managing Gigabytes");
    addDocument(indexWriter, "The Art of Computer Science");
    indexWriter.close();

    Query query = new PrefixQuery(new Term("title", "lucene"));

    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, 10);
    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        System.out.println(searcher.doc(scoreDoc.doc).get("title"));
    }
</code>```

Is there an easy way to solve this? It appears that PrefixQuery is not compatible with StringField, and I can't find a tokenizer that doesn't split on whitespace.

答:
When you index a text field in solr, it will be tokenized. For example, a whitespace tokenizer splits documents upon each space in the scentence. So you might not be able to search based on string positions.

For your use case, you should copy/store this field as a string type(with keyword toeknizer) instead of text. Then you will find solr stores the full scentence as a single string, allowing you to perform regex pattern searches.

Title: Finding strict prefixes in lucene

Body:
I'm trying to implement an autocomplete feature with Lucene. For example, if the user types "Lucene", the returned results may be "Lucene in Action" and "Lucene for Dummies".

The problem I'm having is that the field should start with with the searched text, it shouldn't be somewhere in the middle; searching for "Lucene" shouldn't return "Enterprise Lucene". Here's my code so far, which doesn't exclude the above:

    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);

    IndexWriter indexWriter = new IndexWriter(index, config);
    addDocument(indexWriter, "Luceneinaction");
    addDocument(indexWriter, "LuceneforDummies");
    addDocument(indexWriter, "WhyisLucenesohard");
    addDocument(indexWriter, "Managing Gigabytes");
    addDocument(indexWriter, "The Art of Computer Science");
    indexWriter.close();

    Query query = new PrefixQuery(new Term("title", "lucene"));

    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, 10);
    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        System.out.println(searcher.doc(scoreDoc.doc).get("title"));
    }

Is there an easy way to solve this? It appears that PrefixQuery is not compatible with StringField, and I can't find a tokenizer that doesn't split on whitespace.


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答: In general, queues will offer a "peek" operation which will let you see what's at the top of the queue without removing it, but anything else requires a different data structure. Or else you pop things off the queue and onto another queue until you figure it out, at which point you need to requeue the values you popped off.</p>

ContentLicense: CC BY-SA 2.5


问:
Storing nodes at each level of depth in json object in seperate array
i have a json, something like this </p>

```<code>{
   "a": {
      "b1": "blah blah",
      "b2": "ahsbefbasef",
      "b3": "adsfad af"
   },
   "c": {
      "d1":"asef",
      "d2":"fefef",
      "d3":"ffgfgf"
   }
}
</code>```

<p>now i want to traverse through this json and get all the nodes-depth wise, as in i want to store nodes with 0 depth(a, c) in one array, nodes with depth 1 (c1,c2,c3,d1,d2,d3) in another array, and so on and so forth, basically breaking json object and storing nodes present at each depth in seperate array </p>

答:
You can use below code to achieve your requirements.
and in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

I have benchmarked my code here , you can check below code is faster than accepted answer.

var obj = {
  "a": {
    "b1": "blah blah",
    "b2": "ahsbefbasef",
    "b3": "adsfad af"
  },
  "c": {
    "d1": "asef",
    "d2": "fefef",
    "d3": "ffgfgf"
  }
}

var response = {};
recursive(obj, 0, response);
console.log("result:",response);

function recursive(passedObject, depth, response) {
    var keys = Object.keys(passedObject);
    response[depth] = response[depth] || [];
    response[depth].push(...keys);

    keys.forEach(function(key){
    if (passedObject[key] && typeof passedObject[key] === 'object') {
        recursive(passedObject[key], depth + 1, response)
    }
 })
}```
</div>
</div>
</p>

<p><strong><em>Output:</em></strong></p>

```result:
{
 0 : ["a", "c"]
 1 : ["b1", "b2", "b3", "d1", "d2", "d3"]
}
```

Benchmarking results here:

Body:
i have a json, something like this

{
   "a": {
      "b1": "blah blah",
      "b2": "ahsbefbasef",
      "b3": "adsfad af"
   },
   "c": {
      "d1":"asef",
      "d2":"fefef",
      "d3":"ffgfgf"
   }
}

now i want to traverse through this json and get all the nodes-depth wise, as in i want to store nodes with 0 depth(a, c) in one array, nodes with depth 1 (c1,c2,c3,d1,d2,d3) in another array, and so on and so forth, basically breaking json object and storing nodes present at each depth in seperate array

Body:
You can use below code to achieve your requirements.
and in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

I have benchmarked my code here , you can check below code is faster than accepted answer.

var obj = {
  "a": {
    "b1": "blah blah",
    "b2": "ahsbefbasef",
    "b3": "adsfad af"
  },
  "c": {
    "d1": "asef",
    "d2": "fefef",
    "d3": "ffgfgf"
  }
}

var response = {};
recursive(obj, 0, response);
console.log("result:",response);

function recursive(passedObject, depth, response) {
    var keys = Object.keys(passedObject);
    response[depth] = response[depth] || [];
    response[depth].push(...keys);

    keys.forEach(function(key){
    if (passedObject[key] && typeof passedObject[key] === 'object') {
        recursive(passedObject[key], depth + 1, response)
    }
 })
}

Output:

result:
{
 0 : ["a", "c"]
 1 : ["b1", "b2", "b3", "d1", "d2", "d3"]
}

Benchmarking results here:


问:
CarouselPage with progress indicator?
I have a registration page that has too many fields, that requires me to divide it into 4 pages,
I thought that the best experience is to have a CarouselPage with four ContentPages, that can be easily navigate through, and yet having one view with a corresponding view model.
Before asking the main question, I want to make sure that I'm taking the right decision, and I didn't miss any other option that is dedicated for such case that I'm not aware of (I'm still in my first steps in Xamarin).
if the CarouselPage is the way to go, then I want to have some indicator on the bottom of the screen, that shows the registration progress like a progress bar that increases by 25% on every next page, something that ties all the ContentPages together

答:
You can use the CarouselView which is the successor of CarouselPage. There is a documentation how to implement CarouseView and here is nice blog post.

I can give you good idea how to start. CarouselViev is similar to ListView.

```<code><controls:CarouselViewControl
    x:Name="MyCarouselView">
    <controls:CarouselView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Entry
                    Placeholder="{Binding FirstEntryName}"
                    Text="{Binding FirstEntryText, Mode=TwoWay}"
                    IsVisible="{Binding FirstEntryVisible}" />
                <Entry
                    Placeholder="{Binding SecondEntryName}"
                    Text="{Binding FirstEntryText, Mode=TwoWay}"
                    IsVisible="{Binding SecondEntryVisible}" />
            </StackLayout>
        </DataTemplate>
    </controls:CarouselView.ItemTemplate>
</controls:CarouselViewControl>
</code>```

Then you can populate ItemSource with ObservableCollection DataFromEntries and MyViewData looks like this:

```<code>public class MyViewData
{
    public string FirstEntryName { get; set; }
    public string FirstEntryText { get; set; }
    public bool FirstEntryVisible { get; set; }
    public string SecondEntryName { get; set; }
    public string SecondEntryText { get; set; }
    public bool SecondEntryVisible { get; set; }
}
</code>```

To enable Indicator you need to set property ShowIndicators to true.

Title: CarouselPage with progress indicator?

Body:
You can use the CarouselView which is the successor of CarouselPage. There is a documentation how to implement CarouseView and here is nice blog post.

I can give you good idea how to start. CarouselViev is similar to ListView.

<controls:CarouselViewControl
    x:Name="MyCarouselView">
    <controls:CarouselView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Entry
                    Placeholder="{Binding FirstEntryName}"
                    Text="{Binding FirstEntryText, Mode=TwoWay}"
                    IsVisible="{Binding FirstEntryVisible}" />
                <Entry
                    Placeholder="{Binding SecondEntryName}"
                    Text="{Binding FirstEntryText, Mode=TwoWay}"
                    IsVisible="{Binding SecondEntryVisible}" />
            </StackLayout>
        </DataTemplate>
    </controls:CarouselView.ItemTemplate>
</controls:CarouselViewControl>

Then you can populate ItemSource with ObservableCollection DataFromEntries and MyViewData looks like this:

public class MyViewData
{
    public string FirstEntryName { get; set; }
    public string FirstEntryText { get; set; }
    public bool FirstEntryVisible { get; set; }
    public string SecondEntryName { get; set; }
    public string SecondEntryText { get; set; }
    public bool SecondEntryVisible { get; set; }
}

To enable Indicator you need to set property ShowIndicators to true.


问:
Return a member variable if it exist
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

```<code>struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};
</code>```

or Outgoing:

```<code>struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};
</code>```

The message headers are of only two types:

```<code>struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.
</code>```

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

答:
Since C++ is a statically typed language, you must return both via the same type. As you're only interested in the a and b members of the header structs, one obvious solution is to use have both IncomingHeader and OutgoingHeader derived from a BaseHeader and then return a reference or pointer to that base.

```<code>struct BaseHeader
{
  A a;
  B b;
};

struct IncomingHeader : BaseHeader
{
  /* ... */
} incoming_header;

struct OutgoingHeader : BaseHeader
{
  /* ... */
} outgoing_header;

BaseHeader const&get_header() const
{
  if(/* ... */) return incoming_header;
  return outgoing_header;
}
</code>```

Title: Return a member variable if it exist

Body:
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};

or Outgoing:

struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};

The message headers are of only two types:

struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

Body:
Since C++ is a statically typed language, you must return both via the same type. As you're only interested in the a and b members of the header structs, one obvious solution is to use have both IncomingHeader and OutgoingHeader derived from a BaseHeader and then return a reference or pointer to that base.

struct BaseHeader
{
  A a;
  B b;
};

struct IncomingHeader : BaseHeader
{
  /* ... */
} incoming_header;

struct OutgoingHeader : BaseHeader
{
  /* ... */
} outgoing_header;

BaseHeader const&get_header() const
{
  if(/* ... */) return incoming_header;
  return outgoing_header;
}


问:
Get properties form object and sort by inheritance
I need help sorting an dynamic objects properties by inheritance.

I have a method that should create an ExpandoObject. I'm having trouble with duplicates since "obj.GetType().GetProperties()" takes all the properties regarless of the "new" keyword that is used for hiding properties (note that the baseproperty is inherited from an other project).

My solution is to sort all the properties after inheritance level and proiritize the property in the highest derived class. Baseclass should be the lowest prio.

Is this possible? Look at the second codesnippet to see that I mean.

optional extrainfo:
The inparameter object "obj" in my method is of my class "UserEditModel" see inheritance below.
"UserEditModel" derives from "UserModel",
"UserModel" derives from "Otherproject.UserModel",
"Otherproject.UserModel" derives from "Otherproject.PageModelBase"

My code right now:

```<code>public static dynamic ToExpando(this object obj)
    {
        if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>;
        var instanceProps = obj.GetType().GetProperties();

        //Add all properties except baseclass properties
        var excludeBaseClassProp = obj.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
        foreach (var excludeBaseClassPropItem in excludeBaseClassProp)
        {
            d.Add(excludeBaseClassPropItem.Name, excludeBaseClassPropItem.GetValue(obj, null));
        }
        //Add the rest of the properties and prevent duplicates
        foreach (var item in instanceProps)
        {
            if (d.AsEnumerable().Any(p => p.Key.Contains(item.Name)))
                continue;

            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;
    }
</code>```

What I want to do:

```<code>public static dynamic hannes(this object obj)
    {
        if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary

        var props = obj.GetType().GetProperties();
        foreach (var item in props.OrderBy(prop => prop.INHERITANCE_LEVEL)) //<-----WHAT I WANT TO DO!
        {
            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;
    }
</code>```

答:
Thanks for the help Ed Plunkett

This is the result:

```<code>if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>;

        var props = obj.GetType().GetProperties();
        var propertyInfoGroup = props.GroupBy(p => p.Name).Where(g => g.Count() > 1).Select(grp => grp).ToList();

        foreach (var propertyInfoItem in propertyInfoGroup)
        {
            var inheritanceLevelDictionary = new Dictionary<int, int>();
            int level = 0;
            for (int i = 0; i < propertyInfoItem.Count(); i++)
            {
                //Set inheritance levels/depth for each duplicated item and save them in a temp list
                var baseClass = propertyInfoItem.ElementAt(i).PropertyType.BaseType;
                while (baseClass != null)
                {
                    level++;
                    baseClass = baseClass.BaseType;
                }
                inheritanceLevelDictionary.Add(i, level);
                level = 0;
            }

            //Sort the list so the first item will be the one with most inheritances
            var sortedByHighestLevel = inheritanceLevelDictionary.OrderByDescending(k => k.Value).FirstOrDefault();
            var topLevelItem = propertyInfoItem.ElementAt(sortedByHighestLevel.Key);
            d.Add(topLevelItem.Name, topLevelItem.GetValue(obj, null));

            inheritanceLevelDictionary.Clear();
        }
        foreach (var item in props)
        {
            //Duplicated items are handled obove so skip them
            if (d.AsEnumerable().Any(p => p.Key.Equals(item.Name)))
                continue;

            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;
</code>```

Body:
I need help sorting an dynamic objects properties by inheritance.

I have a method that should create an ExpandoObject. I'm having trouble with duplicates since "obj.GetType().GetProperties()" takes all the properties regarless of the "new" keyword that is used for hiding properties (note that the baseproperty is inherited from an other project).

My solution is to sort all the properties after inheritance level and proiritize the property in the highest derived class. Baseclass should be the lowest prio.

Is this possible? Look at the second codesnippet to see that I mean.

optional extrainfo:
The inparameter object "obj" in my method is of my class "UserEditModel" see inheritance below.
"UserEditModel" derives from "UserModel",
"UserModel" derives from "Otherproject.UserModel",
"Otherproject.UserModel" derives from "Otherproject.PageModelBase"

My code right now:

public static dynamic ToExpando(this object obj)
    {
        if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>;
        var instanceProps = obj.GetType().GetProperties();

        //Add all properties except baseclass properties
        var excludeBaseClassProp = obj.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
        foreach (var excludeBaseClassPropItem in excludeBaseClassProp)
        {
            d.Add(excludeBaseClassPropItem.Name, excludeBaseClassPropItem.GetValue(obj, null));
        }
        //Add the rest of the properties and prevent duplicates
        foreach (var item in instanceProps)
        {
            if (d.AsEnumerable().Any(p => p.Key.Contains(item.Name)))
                continue;

            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;
    }

What I want to do:

public static dynamic hannes(this object obj)
    {
        if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary

        var props = obj.GetType().GetProperties();
        foreach (var item in props.OrderBy(prop => prop.INHERITANCE_LEVEL)) //<-----WHAT I WANT TO DO!
        {
            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;
    }

Body:
Thanks for the help Ed Plunkett

This is the result:

if (obj is ExpandoObject || obj is LenientExpandoObject)
            return obj;

        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>;

        var props = obj.GetType().GetProperties();
        var propertyInfoGroup = props.GroupBy(p => p.Name).Where(g => g.Count() > 1).Select(grp => grp).ToList();

        foreach (var propertyInfoItem in propertyInfoGroup)
        {
            var inheritanceLevelDictionary = new Dictionary<int, int>();
            int level = 0;
            for (int i = 0; i < propertyInfoItem.Count(); i++)
            {
                //Set inheritance levels/depth for each duplicated item and save them in a temp list
                var baseClass = propertyInfoItem.ElementAt(i).PropertyType.BaseType;
                while (baseClass != null)
                {
                    level++;
                    baseClass = baseClass.BaseType;
                }
                inheritanceLevelDictionary.Add(i, level);
                level = 0;
            }

            //Sort the list so the first item will be the one with most inheritances
            var sortedByHighestLevel = inheritanceLevelDictionary.OrderByDescending(k => k.Value).FirstOrDefault();
            var topLevelItem = propertyInfoItem.ElementAt(sortedByHighestLevel.Key);
            d.Add(topLevelItem.Name, topLevelItem.GetValue(obj, null));

            inheritanceLevelDictionary.Clear();
        }
        foreach (var item in props)
        {
            //Duplicated items are handled obove so skip them
            if (d.AsEnumerable().Any(p => p.Key.Equals(item.Name)))
                continue;

            d.Add(item.Name, item.GetValue(obj, null));
        }
        return result;


问:
Need help understanding Zend_Form decorator rendering
I have

```<code>$title = new Zend_Form_Element_Text('title', array('size'=>'20'));
$title->setLabel('Title')
               ->addValidator('NotEmpty')
                ->setDecoratorsarray(
        'ViewHelper',
        array(array('dataz'=>'HtmlTag'), array('tag' => 'div', 'class'  => 'input')),
         array('Label', array('tag' => 'td')),
         array('row'=>'HtmlTag', array('tag' => 'div','class'=>'element')),
    );
</code>```

I need help understanding how to set parameters.

Why do we first point ViewHelper not the end?

Why 2 times html tag between the label?

If I change their position, it doesn't render correctly.

Why only in last option would you want to warp elements (label and input) in the div with class "element"? If I only define HtmlTag once it warps only input elements together, not  both label and input.

How do I wrap both elements?

答:
```<code>$title = new Zend_Form_Element_Text('title', array('size'=>'20'));
$title->setLabel('Title')
               ->addValidator('NotEmpty')
                ->setDecorators(array(
        'ViewHelper',
        array(array('dataz'=>'HtmlTag'), array('tag' => 'div', 'class'  => 'input')),
         array('Label', array('tag' => 'td')),
         array('row'=>'HtmlTag', array('tag' => 'div','class'=>'element')),
    ));
</code>```

Sorry it was some mistake in code.

Body:
I have

$title = new Zend_Form_Element_Text('title', array('size'=>'20'));
$title->setLabel('Title')
               ->addValidator('NotEmpty')
                ->setDecoratorsarray(
        'ViewHelper',
        array(array('dataz'=>'HtmlTag'), array('tag' => 'div', 'class'  => 'input')),
         array('Label', array('tag' => 'td')),
         array('row'=>'HtmlTag', array('tag' => 'div','class'=>'element')),
    );

I need help understanding how to set parameters.

Why do we first point ViewHelper not the end?

Why 2 times html tag between the label?

If I change their position, it doesn't render correctly.

Why only in last option would you want to warp elements (label and input) in the div with class "element"? If I only define HtmlTag once it warps only input elements together, not  both label and input.

How do I wrap both elements?

Body:
$title = new Zend_Form_Element_Text('title', array('size'=>'20'));
$title->setLabel('Title')
               ->addValidator('NotEmpty')
                ->setDecorators(array(
        'ViewHelper',
        array(array('dataz'=>'HtmlTag'), array('tag' => 'div', 'class'  => 'input')),
         array('Label', array('tag' => 'td')),
         array('row'=>'HtmlTag', array('tag' => 'div','class'=>'element')),
    ));

Sorry it was some mistake in code.


问:
Which data type holds Oracle sdo_Geometry data type in C#
in Oracle Database, I have got a table which contains as a number, varchar etc variables. in addition, it has sdo_geometry object column. the task I have wanted, I would like to fetch this sdo_geometry data type and assign inside appropriate data type using c#. I will be happy if you solve this issue.

Thanks for now
Best Regards...

答:
I don't know if there's a .NET type you can map directly to that, but you can call Get_WKT to get the well known text.

```<code>SELECT ID, Name, myPolygon.Get_WKT() FROM YourSource
</code>```

You can read that into a SqlGeometry object at run time if you need.

Body:
I don't know if there's a .NET type you can map directly to that, but you can call Get_WKT to get the well known text.

SELECT ID, Name, myPolygon.Get_WKT() FROM YourSource

You can read that into a SqlGeometry object at run time if you need.


问:
LabVIEW 2017 does not open *.vi-File from LabVIEW 2016
On my Windows 10 PC LabVIEW 2017 is installed. A file I created in LabVIEW 2016 at my Uni will not be opened. When I doubleklick, LabVIEW starts normally, but only as if I had opened it without any file. If I start LabVIEW normally and try to open the file out of the program, nothing will happen, not even an error will occur. Why is this?

Note: Right now I am using LabVIEW 2017 in Evaluation-Mode.

答: I found the reason... The file was saved in a subfolder of a folder which name contained a right arrow (→) which is not supported by LabVIEW obviousely...</p>


问:
Jasmine with promises not showing test results
So I have a very basic test where I want to check the type of a Promise response in a test using Jasmine. I'm running a node project and have all of those details set up

```<code>describe('fail assertion', function() {
        it('should be a failure', function(done) {
            myvideopromise.then(function(resp) {
                expect(true).toBe(false);
                done();
            }).catch(done);
        });
    });

describe('list videos', function() {
        it('should return a list of videos', function(done) {
            myvideopromise.then(function(videos) {
                expect(Array.isArray(videos)).toBe(true);
                done();
            }).catch(done);
        });
    });
</code>```

But when I run it I just see this below.

```<code>Started
F.

Failures:
1) video suite fail assertion should be a failure
  Message:
    Expected true to be false.
</code>```

The "F" is red and the "." is green. So it seems like it's properly running the test assertions, but for successes it doesn't seem to be showing the success message. Is there a flag I need to pass or something? I'm calling it using

```<code>jasmine JASMINE_CONFIG_PATH=test/jasmine_config.json
</code>```

And my jasmine_config.json file simply looks like

```<code>{
    "spec_dir": "test/other/",
    "spec_files": [
        "video_tests.js"
    ]
}
</code>```

答:
```<code>describe('fail assertion', function () {
        it('should be a failure', function (done) {
            myvideopromise.then(function (resp) {
                expect(true).toBe(true);
                done();
            }).catch(e => {
                done(e);
            });
        });
    });

  describe('list videos', function () {
        it('should return a list of videos', function (done) {
            myvideopromise.then(function (videos) {
                expect(Array.isArray(videos)).toBe(true);
                done();
            }).catch(e => {
                done(e);// it's a failure case
            });
        });
    });
</code>```

Body:
So I have a very basic test where I want to check the type of a Promise response in a test using Jasmine. I'm running a node project and have all of those details set up

describe('fail assertion', function() {
        it('should be a failure', function(done) {
            myvideopromise.then(function(resp) {
                expect(true).toBe(false);
                done();
            }).catch(done);
        });
    });

describe('list videos', function() {
        it('should return a list of videos', function(done) {
            myvideopromise.then(function(videos) {
                expect(Array.isArray(videos)).toBe(true);
                done();
            }).catch(done);
        });
    });

But when I run it I just see this below.

Started
F.

Failures:
1) video suite fail assertion should be a failure
  Message:
    Expected true to be false.

The "F" is red and the "." is green. So it seems like it's properly running the test assertions, but for successes it doesn't seem to be showing the success message. Is there a flag I need to pass or something? I'm calling it using

jasmine JASMINE_CONFIG_PATH=test/jasmine_config.json

And my jasmine_config.json file simply looks like

{
    "spec_dir": "test/other/",
    "spec_files": [
        "video_tests.js"
    ]
}


问:
How Get Selected Records Counts of Grid in ASP.NET, Using JS?
I have to show selected number of records from Grid, We will selected row by using checkbox column in grid. When I select number of records from grid, I have to show that selected number of records in Label. I have written code in server but page get post back to it take little bit time when I am selecting any records?I want to do this using Java script? Any Idea...</p>

答:
```<code><!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
    <div class="row">
        <input type="checkbox" name="lineup[]" value="1" checked>Tom</input>
        <input type="checkbox" name="lineup[]" value="2">David</input>
        <input type="checkbox" name="lineup[]" value="3">Sarah</input>
    </div>
    <script>
        $(document).ready(function () {
            var count = 0;
            $('checkbox').change(function () {
                count = $("[type='checkbox']:checked").length;
                console.log(count);
            });
        })
    </script>
</body>
</html>
</code>```


问:
Storing Windows passwords
I'm writing (in C# with .NET 3.5) an administrative application which will poll multiple Windows systems for various bits of data. In many cases it will use WMI, but in some cases it may need to read remote registry or remotely execute some command or script on the polled system. This polling will happen at repeating intervals - usually nightly, but can be configured to happen more (or less) frequently. So the poll could happen as often as every 10 minutes or as rarely as once a month. It needs to happen in an automated way, without any human intervention.

These functions will require admin-level access to the polled systems. Now, I expect that in most use cases, there will be a domain, and the polling application can run as a service with Domain Admin (or equivalent) privileges, which means I do not have to worry about storing passwords - the admin setting up the app will define the service's username/password via standard Windows mechanisms.

But there's always a few black sheep out there. The program may run in nondomain environments, or in cases where some polled systems are not members of the domain. In these cases we will have to define a username and password, store them securely, then invoke this user/pass pair at the time we poll that system. So keep in mind - in this case the program being written is the user who sends password to the authenticating system.

I am not sure whether I will need to use a reversible hash which I then decrypt to plaintext at time of use, or if there is some Windows mechanism which would allow me to store and then reuse the hash only. Obviously the second mechanism is preferable; I'd like my program to either never know the password's plaintext value, or know it for the shortest amount of time possible.

I need suggestions for smart and secure ways to accomplish this.

Thanks for looking!

答:
The answer is here:

How to store passwords in Winforms application?

OwnerDisplayName: quux

Title: Storing Windows passwords

LastEditorDisplayName: quux

OwnerDisplayName: 1800 INFORMATION


问:
Picking random element by user defined weights

Possible Duplicate:

  Generating random results by weight in PHP?

I have a web application where users can add 1-20 strings of text and assign a weight to them of how often it should show up. The system would then choose a random string based on the defined weights. What is the best way to go about this? Do the range values for the weight for each string matter? Could I just have the user assign a number (0-100) for each string? How would you go about choosing a random string? (Each choice doesn't worry about what was chosen before, every string has the same odds (based on weight) of being chosen at the start of each call).

答:
I use this function in several PHP game engines:

```<code><?php
/**
 * @param array $values - just the weights
 * @return integer A number between 0 and count($values) - 1
 */
function getBucketFromWeights($values) {
    $total = $currentTotal = $bucket = 0;
    $firstRand = mt_rand(1, 100);

    foreach ($values as $amount) {
        $total += $amount;
    }

    $rand = ($firstRand / 100) * $total;

    foreach ($values as $amount) {
        $currentTotal += $amount;

        if ($rand > $currentTotal) {
            $bucket++;
        }
        else {
            break;
        }
    }

    return $bucket;
}
</code>```

Usage

Suppose I have the user weights in an associative array where each string points to its weight:

```<code>$weighted_strings = array(
    "important string" => 100,
    "terrible string" => 10,
    "never string" => 0,
    // etc
);
</code>```

If I wanted to pull a string based on weight, I'd do this:

```<code>$weights = array_values($weighted_strings);
$strings = array_keys($weighted_strings);
$index = getBucketFromWeights($weights);
$selectedString = $strings[$index];
</code>```

Body:
I use this function in several PHP game engines:

<?php
/**
 * @param array $values - just the weights
 * @return integer A number between 0 and count($values) - 1
 */
function getBucketFromWeights($values) {
    $total = $currentTotal = $bucket = 0;
    $firstRand = mt_rand(1, 100);

    foreach ($values as $amount) {
        $total += $amount;
    }

    $rand = ($firstRand / 100) * $total;

    foreach ($values as $amount) {
        $currentTotal += $amount;

        if ($rand > $currentTotal) {
            $bucket++;
        }
        else {
            break;
        }
    }

    return $bucket;
}

Usage

Suppose I have the user weights in an associative array where each string points to its weight:

$weighted_strings = array(
    "important string" => 100,
    "terrible string" => 10,
    "never string" => 0,
    // etc
);

If I wanted to pull a string based on weight, I'd do this:

$weights = array_values($weighted_strings);
$strings = array_keys($weighted_strings);
$index = getBucketFromWeights($weights);
$selectedString = $strings[$index];


问:
spark.executor.cores can't take effect while using livy
I'm using livy-server-0.2 to run spark job, however, I can't change the default setting for spark.executor.cores, it can't take effect while the other settings can.

It always use 1 core to start an executor.

```<code>yarn     11893 11889  6 21:08 ?        00:00:01
/opt/jdk1.7.0_80/bin/java -server -XX:OnOutOfMemoryError=kill
%p -Xms1024m -Xmx1024m -Djava.io.tmpdir=/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/tmp
-Dspark.driver.port=51553
-Dspark.yarn.app.container.log.dir=/var/log/hadoop-yarn/containers/application_1487813931557_0603/container_1487813931557_0603_01_000026
-XX:MaxPermSize=256m org.apache.spark.executor.CoarseGrainedExecutorBackend
--driver-url spark://CoarseGrainedScheduler@10.1.1.81:51553 --executor-id 19
--hostname master01.yscredit.com --cores 1 --app-id application_1487813931557_0603
--user-class-path file:/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/__app__.jar
</code>```

Here is my spark-defaults.conf file in $SPARK_HOME/conf

```<code>spark.master=yarn
spark.submit.deployMode=cluster
spark.executor.instances=7
spark.executor.cores=6
spark.executor.memoryOverhead=1024
spark.yarn.executor.memoryOverhead=1400
spark.executor.memory=11264
spark.driver.memory=5g
spark.yarn.driver.memoryOverhead=600
spark.speculation=true
spark.yarn.executor.memoryOverhead=1400
</code>```

can anybody help me? thanks!

答:
I strongly advise you to read the Livy source code.I think Livy has little documentation , so ,you might meet many problems which cannot be solved by google.Livy is just a middleware， amount of code is relatively small.

You can specify the spark parameter from 3 locations:

Location A: If you have already set the spark parameter in
your creating-session post request to LivyServer ,then any
configuration occured at your post request can not be overrided by any configuration file.That is to say, configuration at your post request has the highest priority;

Location B: Then , at $LIVY_HOME/conf，you can set spark parameters
like 'spark.driver.memory' at spark-defaults.conf or
livy-client.conf;

Location C: At last , Livy will also use configuration at
$SPARK_HOME/conf/spark-defaults.conf,but configuration here has the
lowest priority,that is to say , only configuration that did't occur
at Location A/B will take effect.

Body:
I'm using livy-server-0.2 to run spark job, however, I can't change the default setting for spark.executor.cores, it can't take effect while the other settings can.

It always use 1 core to start an executor.

yarn     11893 11889  6 21:08 ?        00:00:01
/opt/jdk1.7.0_80/bin/java -server -XX:OnOutOfMemoryError=kill
%p -Xms1024m -Xmx1024m -Djava.io.tmpdir=/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/tmp
-Dspark.driver.port=51553
-Dspark.yarn.app.container.log.dir=/var/log/hadoop-yarn/containers/application_1487813931557_0603/container_1487813931557_0603_01_000026
-XX:MaxPermSize=256m org.apache.spark.executor.CoarseGrainedExecutorBackend
--driver-url spark://CoarseGrainedScheduler@10.1.1.81:51553 --executor-id 19
--hostname master01.yscredit.com --cores 1 --app-id application_1487813931557_0603
--user-class-path file:/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/__app__.jar

Here is my spark-defaults.conf file in $SPARK_HOME/conf

spark.master=yarn
spark.submit.deployMode=cluster
spark.executor.instances=7
spark.executor.cores=6
spark.executor.memoryOverhead=1024
spark.yarn.executor.memoryOverhead=1400
spark.executor.memory=11264
spark.driver.memory=5g
spark.yarn.driver.memoryOverhead=600
spark.speculation=true
spark.yarn.executor.memoryOverhead=1400

can anybody help me? thanks!


问:
MySQL Function to add a number of working days to a DATETIME
I need a MySQL Function that will allow me to pass a number of working days (Monday - Friday) and a start DATE or DATETIME (doesn't matter for my implementation), and have it return a new DATE or DATETIME that many work days in the future.

Example: SELECT AddWorkDays(10, "2013-09-01") returns "2013-09-16" assuming "2013-09-01" is a Monday.

Similarly: SELECT AddWorkDays(-10, "2013-09-16") returns "2013-09-01"

I found this function for an MSSQL database (I think) that is exactly what I need except its not in MySQL. I tried to manually convert it into MySQL syntax and got about this far:

```<code>DROP FUNCTION IF EXISTS AddWorkDays;
DELIMITER $$
CREATE FUNCTION AddWorkDays
(
    WorkingDays INT,
    StartDate DATE
)
RETURNS DATE

BEGIN
    DECLARE Count INT;
    DECLARE i INT;
    DECLARE NewDate DATE;
    SET Count = 0;
    SET i = 0;

    WHILE (i < WorkingDays) DO
        BEGIN
            SET Count = Count + 1;
            SET i = i + 1;
            WHILE DAYOFWEEK(ADDDATE(StartDate, Count)) IN (1,7) DO
                BEGIN
                    SET Count = Count + 1;
                END;
            END WHILE;
        END;
    END WHILE;

    SET NewDate = ADDDATE(StartDate, Count);
    RETURN NewDate;

END;
$$

DELIMITER ;
</code>```

I end up getting an error:

Error 1415: Not allowed to return a result set from a function

I can't seem to figure out where exactly it is trying to return a result set.

Is there an error in my syntax? Are there any better solutions?

Thanks!

EDIT

It appears MySQL doesn't have a DATEPART or DATEADD function. I see in the documentation that they have ADDDATE and DAYOFWEEK. Updated the code to represent this. I also changed the SELECT statements to SET (Makes sense now why I was getting the original error)

As a result I get a new error when attempting to run a query using the function via CF

```<code>[Table (rows 1 columns ADDWORKDAYS(10,"2013-09-01")): [ADDWORKDAYS(10,"2013-09-01"): coldfusion.sql.QueryColumn@7a010] ] is not indexable by ADDWORKDAYS(10
</code>```

答:
```<code>FUNCTION `WORKDAY_ADD`(mydate DATE, numday INT) RETURNS date
BEGIN
DECLARE num_day INT DEFAULT 0;
DECLARE adj INT DEFAULT 0;
DECLARE total INT DEFAULT 0;
SET num_week = ABS(numday DIV 5);
SET num_day = MOD(numday, 5);

IF  numday > 0 and (WEEKDAY(DATE_ADD(mydate, INTERVAL num_day DAY)) < WEEKDAY(mydate)) THEN
    SET adj = 2;
END IF;

IF  numday < 0 and (WEEKDAY(DATE_ADD(mydate, INTERVAL num_day DAY)) > WEEKDAY(mydate)) THEN
    SET adj = 2;
END IF;

SET total = (num_week * 7 + adj + ABS(num_day));

IF numday < 0 THEN
    SET total = total * -1;
END IF;

RETURN DATE_ADD(mydate, INTERVAL total DAY);

END
</code>```

<p>Hi all, needed a formula that would go backwards and forwards. I used one above but spotted an error. I have corrected it now and the formula is working well. </p>

Body:
I need a MySQL Function that will allow me to pass a number of working days (Monday - Friday) and a start DATE or DATETIME (doesn't matter for my implementation), and have it return a new DATE or DATETIME that many work days in the future.

Example: SELECT AddWorkDays(10, "2013-09-01") returns "2013-09-16" assuming "2013-09-01" is a Monday.

Similarly: SELECT AddWorkDays(-10, "2013-09-16") returns "2013-09-01"

I found this function for an MSSQL database (I think) that is exactly what I need except its not in MySQL. I tried to manually convert it into MySQL syntax and got about this far:

DROP FUNCTION IF EXISTS AddWorkDays;
DELIMITER $$
CREATE FUNCTION AddWorkDays
(
    WorkingDays INT,
    StartDate DATE
)
RETURNS DATE

BEGIN
    DECLARE Count INT;
    DECLARE i INT;
    DECLARE NewDate DATE;
    SET Count = 0;
    SET i = 0;

    WHILE (i < WorkingDays) DO
        BEGIN
            SET Count = Count + 1;
            SET i = i + 1;
            WHILE DAYOFWEEK(ADDDATE(StartDate, Count)) IN (1,7) DO
                BEGIN
                    SET Count = Count + 1;
                END;
            END WHILE;
        END;
    END WHILE;

    SET NewDate = ADDDATE(StartDate, Count);
    RETURN NewDate;

END;
$$

DELIMITER ;

I end up getting an error:

Error 1415: Not allowed to return a result set from a function

I can't seem to figure out where exactly it is trying to return a result set.

Is there an error in my syntax? Are there any better solutions?

Thanks!

EDIT

It appears MySQL doesn't have a DATEPART or DATEADD function. I see in the documentation that they have ADDDATE and DAYOFWEEK. Updated the code to represent this. I also changed the SELECT statements to SET (Makes sense now why I was getting the original error)

As a result I get a new error when attempting to run a query using the function via CF

[Table (rows 1 columns ADDWORKDAYS(10,"2013-09-01")): [ADDWORKDAYS(10,"2013-09-01"): coldfusion.sql.QueryColumn@7a010] ] is not indexable by ADDWORKDAYS(10

Body:
FUNCTION `WORKDAY_ADD`(mydate DATE, numday INT) RETURNS date
BEGIN
DECLARE num_day INT DEFAULT 0;
DECLARE adj INT DEFAULT 0;
DECLARE total INT DEFAULT 0;
SET num_week = ABS(numday DIV 5);
SET num_day = MOD(numday, 5);

IF  numday > 0 and (WEEKDAY(DATE_ADD(mydate, INTERVAL num_day DAY)) < WEEKDAY(mydate)) THEN
    SET adj = 2;
END IF;

IF  numday < 0 and (WEEKDAY(DATE_ADD(mydate, INTERVAL num_day DAY)) > WEEKDAY(mydate)) THEN
    SET adj = 2;
END IF;

SET total = (num_week * 7 + adj + ABS(num_day));

IF numday < 0 THEN
    SET total = total * -1;
END IF;

RETURN DATE_ADD(mydate, INTERVAL total DAY);

END

Hi all, needed a formula that would go backwards and forwards. I used one above but spotted an error. I have corrected it now and the formula is working well.


问:
How to hold a table of data for user edition (before saving in the the database)?
I've been using this programming style, that I've seen in an example and just started using it, because it does the job... I would like to know other programmers' opinion about it...

So the situation is when you have a GridView, or a control based on it like the RadGrid, and you want to keep track of a data table while you are adding, editing, reordering and deleting rows.

Using the session to hold the data table (or list of data) may not be the best solution, because the user may open two identical web pages… Using the ViewState to hold the data may be and option... I have been using an approach like the following:

```<code>public partial class DefaultPage : System.Web.UI.Page
{
    protected DataLine DefaultDataLine()
    {
        DataLine dl = new DataLine();

        dl = new DataLine();
        dl.Number = 0;
        dl.Title = "";
        dl.Text = "";
        return dl;
    }

    protected class DataLine
    {
        public int Number { get; set; }
        public string Title { get; set; }
        public string Text { get; set; }
    }

    protected static List<DataLine> tempLines;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            tempLines = RadGridBindStartUpData();
        }
    }

    protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = tempLines;
    }

    protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;

        List<DataLine> table = tempLines;

        DataLine newRow = new DataLine ();

        RadTextBox rtb;
        rtb = (RadTextBox)editedItem.FindControl("RadTextBoxTitle");
        newRow.Title = rtb.Text;
        rtb = (RadTextBox)editedItem.FindControl("RadTextBoxDescription");
        newRow.Description = rtb.Text;

        RadNumericTextBox number =  (RadNumericTextBox)editedItem.FindControl("RadNumericTextBoxNumber");
        newRow.Number = number.Value.HasValue ? Convert.ToInt32(number.Value.Value) : 0;

        table.Add(newRow);
    }

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

So using a static List variable, of a custom object (class), declared in the code-behind of the Aspx page, and updating it whenever the data is edited.

What are your thoughts about this approach? Is it okay? How do you hold your table-format data for edition (prior to saving it in the database)?

答:
You mentioned storing in the session, and how this could cause issues if the user opens up multiple copies of the page, etc...

We had a similar issue so I made a property in code behind on the page and on first page load (if not postback blah blah) I generate a new guid.  Then I use the guid value as my session key and I know it'll be unique per page.

You could make a spify property like this...

```<code>Public ReadOnly Property SessionDataKey() As String
    Get
        If ViewState("SessionDataKey") Is Nothing Then
            ViewState("SessionDataKey") = Guid.NewGuid()
        End If

        Return ViewState("SessionDataKey").ToString()
    End Get
End Property
</code>```

But in short, I just use the session.

Body:
I've been using this programming style, that I've seen in an example and just started using it, because it does the job... I would like to know other programmers' opinion about it...

So the situation is when you have a GridView, or a control based on it like the RadGrid, and you want to keep track of a data table while you are adding, editing, reordering and deleting rows.

Using the session to hold the data table (or list of data) may not be the best solution, because the user may open two identical web pages… Using the ViewState to hold the data may be and option... I have been using an approach like the following:

public partial class DefaultPage : System.Web.UI.Page
{
    protected DataLine DefaultDataLine()
    {
        DataLine dl = new DataLine();

        dl = new DataLine();
        dl.Number = 0;
        dl.Title = "";
        dl.Text = "";
        return dl;
    }

    protected class DataLine
    {
        public int Number { get; set; }
        public string Title { get; set; }
        public string Text { get; set; }
    }

    protected static List<DataLine> tempLines;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            tempLines = RadGridBindStartUpData();
        }
    }

    protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = tempLines;
    }

    protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;

        List<DataLine> table = tempLines;

        DataLine newRow = new DataLine ();

        RadTextBox rtb;
        rtb = (RadTextBox)editedItem.FindControl("RadTextBoxTitle");
        newRow.Title = rtb.Text;
        rtb = (RadTextBox)editedItem.FindControl("RadTextBoxDescription");
        newRow.Description = rtb.Text;

        RadNumericTextBox number =  (RadNumericTextBox)editedItem.FindControl("RadNumericTextBoxNumber");
        newRow.Number = number.Value.HasValue ? Convert.ToInt32(number.Value.Value) : 0;

        table.Add(newRow);
    }

    // ...

So using a static List variable, of a custom object (class), declared in the code-behind of the Aspx page, and updating it whenever the data is edited.

What are your thoughts about this approach? Is it okay? How do you hold your table-format data for edition (prior to saving it in the database)?

Body:
You mentioned storing in the session, and how this could cause issues if the user opens up multiple copies of the page, etc...

We had a similar issue so I made a property in code behind on the page and on first page load (if not postback blah blah) I generate a new guid.  Then I use the guid value as my session key and I know it'll be unique per page.

You could make a spify property like this...

Public ReadOnly Property SessionDataKey() As String
    Get
        If ViewState("SessionDataKey") Is Nothing Then
            ViewState("SessionDataKey") = Guid.NewGuid()
        End If

        Return ViewState("SessionDataKey").ToString()
    End Get
End Property

But in short, I just use the session.


问:
How to select identical rows from a pandas dataframe along with null
I'm new to pandas and I'm having problem with row selections from dataframe.

Following is my DataFrame :

```<code> Index Column1 Column2 Column3       Column4  Column5
   0   1234    500     NEWYORK       NY       NaN
   1   5678    700     AUSTIN        TX       5678956010
   2   1234    300     NEWYORKCITY   NY       NaN
   3   8910    235     RICHMOND      FL       8484883666
   4   8910    250     AUSTIN        TX       8484883666
   5   5324    150     AUSTIN        TX       NaN
</code>```

1.) I want to select rows that are having same values in Column5. So the output dataframe should contain rows with index 0,2,3 and 4. Note that two rows with NaN in Column 5 should be selected only if their Column1 value is same(example. rows with index 0 and 2).

Can any one help me with a step-by-step procedure for this custom selection. Thanks in advance...

答:
You can just use:</p>

```<code>df[df.duplicated(['Column1', 'Column5'], keep=False)
#Index Column1 Column2 Column3       Column4  Column5
#  0   1234    500     NEWYORK       NY       NaN
#  2   1234    300     NEWYORKCITY   NY       NaN
#  3   8910    235     RICHMOND      FL       8484883666
#  4   8910    250     AUSTIN        TX       8484883666
</code>```

Body:
I'm new to pandas and I'm having problem with row selections from dataframe.

Following is my DataFrame :

 Index Column1 Column2 Column3       Column4  Column5
   0   1234    500     NEWYORK       NY       NaN
   1   5678    700     AUSTIN        TX       5678956010
   2   1234    300     NEWYORKCITY   NY       NaN
   3   8910    235     RICHMOND      FL       8484883666
   4   8910    250     AUSTIN        TX       8484883666
   5   5324    150     AUSTIN        TX       NaN

1.) I want to select rows that are having same values in Column5. So the output dataframe should contain rows with index 0,2,3 and 4. Note that two rows with NaN in Column 5 should be selected only if their Column1 value is same(example. rows with index 0 and 2).

Can any one help me with a step-by-step procedure for this custom selection. Thanks in advance...

Body:
You can just use:

df[df.duplicated(['Column1', 'Column5'], keep=False)
#Index Column1 Column2 Column3       Column4  Column5
#  0   1234    500     NEWYORK       NY       NaN
#  2   1234    300     NEWYORKCITY   NY       NaN
#  3   8910    235     RICHMOND      FL       8484883666
#  4   8910    250     AUSTIN        TX       8484883666


问:
Does javassist let modify an operator in a conditional expression?
I need to know if with the following code and with javassist I can manipulate the code to replace the logical operator ">" with "<".

Here is the class whose bytecode I want to manipulate:

```<code>public class TryClass {
    public void foo(){
        int a =0;
        if(a>5){
            System.out.println("I love apples");
       }
        else{
            System.out.println("I hate apples");
       }
    }
}
</code>```

After the manipulation the execution of the class should print:
    "I love apples"
instead of:
    "I hate apples"

答:
The common pattern for altering expressions in method bodies is using ExprEditor and specific subclasses of Expr which include the following types of expressions(at the time of writing):

type cast

constructor call

field access

catch clause

instanceof expression

method call

new array expression

new expression

However none of these include comparison expressions. And you can confirm this by looking at the source of ExprEditor::loopBody:

```<code>       if (c < Opcode.GETSTATIC)   // c < 178
            /* skip */;
</code>```

Comparison opcodes such as if_icmple = 164 are skipped.

Javassist is frequently used due to its high-level instrumentation API, however it also has a bytecode level API under the javassist.bytecode package. This means you can go over the opcodes in the method bytecode and swap them around.

First we need to determine the bytecode of the foo method and expression we wish to alter(e.g. using javap):

```<code>   0: iconst_0
   1: istore_1
   2: iload_1
   3: iconst_5
   4: if_icmple     18
   7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  10: ldc           #3                  // String I love apples
  12: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  15: goto          26
  18: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  21: ldc           #5                  // String I hate apples
  23: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  26: return
</code>```

As we can see, the a > 5 was compiled into an if_icmple(<=) compare and branch to else block, which is a common pattern for compilers handling if expressions.
To flip the expression in your example, we just need to swap if_icmple with if_icmpgt.

The following code demonstrates how to do it using the Javassist bytecode API:

```<code>CtClass cc = ClassPool.getDefault().get("TryClass");
CtMethod fooMethod = cc.getDeclaredMethod("foo");

CodeIterator codeIterator = fooMethod.getMethodInfo().getCodeAttribute().iterator();
while (codeIterator.hasNext()) {
  int pos = codeIterator.next();
  int opcode = codeIterator.byteAt(pos);

  if(opcode == Opcode.IF_ICMPLE) {
    codeIterator.writeByte(Opcode.IF_ICMPGT, pos);
    break;
  }
}

TryClass test = (TryClass) cc.toClass().newInstance();
test.foo();
</code>```

However this code doesn't do any additional checks to ensure the intended expression was changed. Some suggestions may be to check which operands are on the stack during the comparison. If one of them was loaded from a local variable slot, you may use information from the LocalVariableTable(if available) CodeAttribute to match variable names for example.

Body:
I need to know if with the following code and with javassist I can manipulate the code to replace the logical operator ">" with "<".

Here is the class whose bytecode I want to manipulate:

public class TryClass {
    public void foo(){
        int a =0;
        if(a>5){
            System.out.println("I love apples");
       }
        else{
            System.out.println("I hate apples");
       }
    }
}

After the manipulation the execution of the class should print:
    "I love apples"
instead of:
    "I hate apples"

Body:
The common pattern for altering expressions in method bodies is using ExprEditor and specific subclasses of Expr which include the following types of expressions(at the time of writing):

type cast

constructor call

field access

catch clause

instanceof expression

method call

new array expression

new expression

However none of these include comparison expressions. And you can confirm this by looking at the source of ExprEditor::loopBody:

       if (c < Opcode.GETSTATIC)   // c < 178
            /* skip */;

Comparison opcodes such as if_icmple = 164 are skipped.

Javassist is frequently used due to its high-level instrumentation API, however it also has a bytecode level API under the javassist.bytecode package. This means you can go over the opcodes in the method bytecode and swap them around.

First we need to determine the bytecode of the foo method and expression we wish to alter(e.g. using javap):

   0: iconst_0
   1: istore_1
   2: iload_1
   3: iconst_5
   4: if_icmple     18
   7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  10: ldc           #3                  // String I love apples
  12: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  15: goto          26
  18: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  21: ldc           #5                  // String I hate apples
  23: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  26: return

As we can see, the a > 5 was compiled into an if_icmple(<=) compare and branch to else block, which is a common pattern for compilers handling if expressions.
To flip the expression in your example, we just need to swap if_icmple with if_icmpgt.

The following code demonstrates how to do it using the Javassist bytecode API:

CtClass cc = ClassPool.getDefault().get("TryClass");
CtMethod fooMethod = cc.getDeclaredMethod("foo");

CodeIterator codeIterator = fooMethod.getMethodInfo().getCodeAttribute().iterator();
while (codeIterator.hasNext()) {
  int pos = codeIterator.next();
  int opcode = codeIterator.byteAt(pos);

  if(opcode == Opcode.IF_ICMPLE) {
    codeIterator.writeByte(Opcode.IF_ICMPGT, pos);
    break;
  }
}

TryClass test = (TryClass) cc.toClass().newInstance();
test.foo();

However this code doesn't do any additional checks to ensure the intended expression was changed. Some suggestions may be to check which operands are on the stack during the comparison. If one of them was loaded from a local variable slot, you may use information from the LocalVariableTable(if available) CodeAttribute to match variable names for example.


问:
Select rows which do not have duplicates
I have following SQL table:

```<code>+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+
</code>```

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

```<code>+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+
</code>```

How can I do this in tsql?

答:
Using Window Function also we get the same result

```<code>SELECT Account FROM
(
SELECT Account,
     COUNT(Account)OVER(Partition by Account ORDER BY Account) AS DistinctCnt
FROM cte
)
DT WHERE DT.DistinctCnt=1
</code>```

Result

```<code>Account
--------
11100013
11100014
11100015
</code>```

Body:
I have following SQL table:

+--------------+
| Account      |
+--------------+
|    11100011  |
|    11100012  |
|    11100013  |
|    11100014  |
|    11100011  |
|    11100012  |
|    11100015  |
+--------------+

What I need is to make a select query with rows that do not have any duplicates in this table (i.e. removing both duplicated rows), so query result will look like this

+--------------+
| Account      |
+--------------+
|    11100013  |
|    11100014  |
|    11100015  |
+--------------+

How can I do this in tsql?

Body:
Using Window Function also we get the same result

SELECT Account FROM
(
SELECT Account,
     COUNT(Account)OVER(Partition by Account ORDER BY Account) AS DistinctCnt
FROM cte
)
DT WHERE DT.DistinctCnt=1

Result

Account
--------
11100013
11100014
11100015


问:
unable to use the variable declared outside the render function
why is that when we declare a object outside the render function and using it in the return of the render function of a component causes an unexpected token error . If i declare the myStyle object inside the render function the below code works correctly.  </p>

```<code>import React , { Component } from 'react';

class Test extends Component {

  var myStyle={
      backgroundColor:"red",
      width:"100px",
      height:"100px",
      margin:"0 auto",
      marginTop:"50px"
  };

  render(){
    return(
       <div style={myStyle}>

      </div>
    );
  }
}

export default Test;
</code>```

<p>Thanks </p>

答:
First, since you're using ES6 class syntax, you should use const or let to define your variables.

The best solution for you though would be to set the variable into the state of the component. So you can manipulate the state easily later and rerender the component when needed with this.setState();.

You would do it like this:

Inside the constructor method you would do -

```<code>constructor(props){
    super(props);

    this.state = {
        myStyle: {
            backgroundColor:"red",
            width:"100px",
            height:"100px",
            margin:"0 auto",
            marginTop:"50px"
        }
    }
}
</code>```

After that, you can use the ES6 spread operator to apply the CSS to whatever component you like, easily.

Body:
why is that when we declare a object outside the render function and using it in the return of the render function of a component causes an unexpected token error . If i declare the myStyle object inside the render function the below code works correctly.

import React , { Component } from 'react';

class Test extends Component {

  var myStyle={
      backgroundColor:"red",
      width:"100px",
      height:"100px",
      margin:"0 auto",
      marginTop:"50px"
  };

  render(){
    return(

    );
  }
}

export default Test;

Thanks

Body:
First, since you're using ES6 class syntax, you should use const or let to define your variables.

The best solution for you though would be to set the variable into the state of the component. So you can manipulate the state easily later and rerender the component when needed with this.setState();.

You would do it like this:

Inside the constructor method you would do -

constructor(props){
    super(props);

    this.state = {
        myStyle: {
            backgroundColor:"red",
            width:"100px",
            height:"100px",
            margin:"0 auto",
            marginTop:"50px"
        }
    }
}

After that, you can use the ES6 spread operator to apply the CSS to whatever component you like, easily.


问:
Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged
In my Android project, I have had to add a TextChangedListener (TextWatcher) to an edit text view. And there are three parts to it:

onTextChanged()

beforeTextChanged()

afterTextChanged()

What are the differences of these three? I have had to implement a search of a table on the key listener and for my case all these three looked the same. Also they functioned the same. When I input a part of a product name, the table redraws with only those products that contain entered text in it. But I used the afterTextChanged() part. My code is:

```<code>EditProduct.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

            // System.out.println("onTextChanged"+s);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub
            // System.out.println("beforeTextChanged"+s);
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            // System.out.println("afterTextChanged"+s);

            String new_prx = s.toString();

            System.out.println(s);
            mini_productList = new ArrayList<Product>();

            // mini_productList
            int count = 0;
            if (new_prx.equals("")) {

                loadtableProducts(productList);

            } else {

                for (int i = 0; i < productList.size(); i++) {

                    if (productList.get(i).getDescription().toString()
                            .substring(0, (new_prx.length()))
                            .equalsIgnoreCase(new_prx)) {
                        mini_productList.add(productList.get(i));
                        count++;

                    }
                }

                loadtableProducts(mini_productList);
            }
        }
    });
</code>```

So can someone give me an explanation on these three?

答:
The parameters for beforeTextChanged and onTextChanged are a little hard to understand at first. It may be helpful to see them being used in an example. Watch the following demonstration a few times. Pay attention to the counts.

The red highlight is the old text that is about to be replaced by the green text.

The green highlight is the new text that just replaced the red text.

beforeTextChanged

start is the start index of the red highlighted text (that is about to be deleted)

count is the length of the red highlighted text (that is about to be deleted)

after is the length of the green highlighted text (that is about to be added)

onTextChanged

start is the start index of the green highlighted text (that just got added).

This is the same as the start of beforeTextChanged.

before is the length of the red highlighted text (that just got deleted).

This is the same as the count of beforeTextChanged.

count is the length of the green highlighted text (that just got added).

This is the same as the after of beforeTextChanged.

afterTextChanged

editable is the editable text from the EditText. You are allowed to change it here. Doing so will trigger all the TextWatcher events again.

You are not given any information about what was changed. If you want to know, you can set a span in onTextChanged and then look up the span here.

When to use which?

If you want to observe the changes being made, use beforeTextChanged() or onTextChanged(). You are not allowed to change the CharSequence text in either of these methods, though.

If you want to further modify the text after it was changed, do it in afterTextChanged().

Code

Here is the code if you want to play around with it yourself.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    final static int RED_COLOR = Color.parseColor("#fb7373");
    final static int GREEN_COLOR = Color.parseColor("#40de83");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText editText = findViewById(R.id.editText);
        final TextView tvBeforeText = findViewById(R.id.tvBeforeText);
        final TextView tvBeforeNumbers = findViewById(R.id.tvBeforeNumbers);
        final TextView tvAfterText = findViewById(R.id.tvAfterText);
        final TextView tvAfterNumbers = findViewById(R.id.tvAfterNumbers);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                SpannableString spannableString = new SpannableString(s);
                BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(RED_COLOR);
                spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvBeforeText.setText(spannableString);
                tvBeforeNumbers.setText("start=" + start + "  count=" + count + " after=" + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SpannableString spannableString = new SpannableString(s);
                BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(GREEN_COLOR);
                spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvAfterText.setText(spannableString);
                tvAfterNumbers.setText("start=" + start + " before=" + before + " count=" + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i("TAG", "afterTextChanged: " + s);
            }
        });
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="beforeTextChanged" />

    <TextView
        android:id="@+id/tvBeforeText"
        android:textSize="17sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvBeforeNumbers"
        android:textSize="17sp"
        android:text="start=0 count=0 after=0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:text="onTextChanged" />

    <TextView
        android:id="@+id/tvAfterText"
        android:textSize="17sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvAfterNumbers"
        android:textSize="17sp"
        android:text="start=0 count=0 after=0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

Body:
In my Android project, I have had to add a TextChangedListener (TextWatcher) to an edit text view. And there are three parts to it:

onTextChanged()

beforeTextChanged()

afterTextChanged()

What are the differences of these three? I have had to implement a search of a table on the key listener and for my case all these three looked the same. Also they functioned the same. When I input a part of a product name, the table redraws with only those products that contain entered text in it. But I used the afterTextChanged() part. My code is:

EditProduct.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

            // System.out.println("onTextChanged"+s);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub
            // System.out.println("beforeTextChanged"+s);
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            // System.out.println("afterTextChanged"+s);

            String new_prx = s.toString();

            System.out.println(s);
            mini_productList = new ArrayList<Product>();

            // mini_productList
            int count = 0;
            if (new_prx.equals("")) {

                loadtableProducts(productList);

            } else {

                for (int i = 0; i < productList.size(); i++) {

                    if (productList.get(i).getDescription().toString()
                            .substring(0, (new_prx.length()))
                            .equalsIgnoreCase(new_prx)) {
                        mini_productList.add(productList.get(i));
                        count++;

                    }
                }

                loadtableProducts(mini_productList);
            }
        }
    });

So can someone give me an explanation on these three?

Body:
The parameters for beforeTextChanged and onTextChanged are a little hard to understand at first. It may be helpful to see them being used in an example. Watch the following demonstration a few times. Pay attention to the counts.

The red highlight is the old text that is about to be replaced by the green text.

The green highlight is the new text that just replaced the red text.

beforeTextChanged

start is the start index of the red highlighted text (that is about to be deleted)

count is the length of the red highlighted text (that is about to be deleted)

after is the length of the green highlighted text (that is about to be added)

onTextChanged

start is the start index of the green highlighted text (that just got added).

This is the same as the start of beforeTextChanged.

before is the length of the red highlighted text (that just got deleted).

This is the same as the count of beforeTextChanged.

count is the length of the green highlighted text (that just got added).

This is the same as the after of beforeTextChanged.

afterTextChanged

editable is the editable text from the EditText. You are allowed to change it here. Doing so will trigger all the TextWatcher events again.

You are not given any information about what was changed. If you want to know, you can set a span in onTextChanged and then look up the span here.

When to use which?

If you want to observe the changes being made, use beforeTextChanged() or onTextChanged(). You are not allowed to change the CharSequence text in either of these methods, though.

If you want to further modify the text after it was changed, do it in afterTextChanged().

Code

Here is the code if you want to play around with it yourself.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    final static int RED_COLOR = Color.parseColor("#fb7373");
    final static int GREEN_COLOR = Color.parseColor("#40de83");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText editText = findViewById(R.id.editText);
        final TextView tvBeforeText = findViewById(R.id.tvBeforeText);
        final TextView tvBeforeNumbers = findViewById(R.id.tvBeforeNumbers);
        final TextView tvAfterText = findViewById(R.id.tvAfterText);
        final TextView tvAfterNumbers = findViewById(R.id.tvAfterNumbers);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                SpannableString spannableString = new SpannableString(s);
                BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(RED_COLOR);
                spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvBeforeText.setText(spannableString);
                tvBeforeNumbers.setText("start=" + start + "  count=" + count + " after=" + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SpannableString spannableString = new SpannableString(s);
                BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(GREEN_COLOR);
                spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvAfterText.setText(spannableString);
                tvAfterNumbers.setText("start=" + start + " before=" + before + " count=" + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i("TAG", "afterTextChanged: " + s);
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="beforeTextChanged" />

    <TextView
        android:id="@+id/tvBeforeText"
        android:textSize="17sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvBeforeNumbers"
        android:textSize="17sp"
        android:text="start=0 count=0 after=0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:text="onTextChanged" />

    <TextView
        android:id="@+id/tvAfterText"
        android:textSize="17sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvAfterNumbers"
        android:textSize="17sp"
        android:text="start=0 count=0 after=0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


问:
Bulk register IEntityTypeConfiguration<> entity framework core
Ok, so i am using entity framework with dot net core and code first migrations. This isn't a problem as such, i just wondered if anyone had come across a better way of doing this.

Currently i have many entity type configurations like so

```<code>public class ExampleEntityConfiguration : IEntityTypeConfiguration<ExampleEntity>
{
   public void Configure(EntityTypeBuilder<ExampleEntity> builder)
   {
      builder.Property(p => p.Id).ValueGeneratedNever();

      // more options here
   }
}
</code>```

and i register them in my dbcontext like so

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);

  modelBuilder.ApplyConfiguration(new ExampleEntityConfiguration());

  // lot's more configurations here
}
</code>```

has anyone come across or know of a way to register all the IEntityTypeConfiguration interfaces?

It just seems like a lot of repetitive code that could be solved by getting a list of the configurations, looping over them and applying in the context. I just don't know where to start with getting a list of IEntityTypeConfiguration classes that exist in a particular namespace.

Any help/suggestions would be great.

答:
The nice work from @Evk kan be further encapsulated in a reusable extension method:

```<code> public static class ModelBuilderExtensions
{
    public static void ApplyAllConfigurationsFromCurrentAssembly(this ModelBuilder modelBuilder, Assembly assembly, string configNamespace = "")
    {
        var applyGenericMethods = typeof(ModelBuilder).GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
        var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m=>m.GetParameters().FirstOrDefault().ParameterType.Name== "IEntityTypeConfiguration`1").FirstOrDefault();

        var applicableTypes = assembly
            .GetTypes()
            .Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters);

        if (!string.IsNullOrEmpty(configNamespace))
        {
            applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
        }

        foreach (var type in applicableTypes)
        {
            foreach (var iface in type.GetInterfaces())
            {
                // if type implements interface IEntityTypeConfiguration<SomeEntity>
                if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
                {
                    // make concrete ApplyConfiguration<SomeEntity> method
                    var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                    // and invoke that with fresh instance of your configuration type
                    applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
                    Console.WriteLine("applied model " + type.Name);
                    break;
                }
            }
        }
    }
}
</code>```

And can be called as such:

```<code>public class ApiDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyAllConfigurationsFromCurrentAssembly("MyRoot.Api.Entities.Configuration");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }
}
</code>```

Body:
Ok, so i am using entity framework with dot net core and code first migrations. This isn't a problem as such, i just wondered if anyone had come across a better way of doing this.

Currently i have many entity type configurations like so

public class ExampleEntityConfiguration : IEntityTypeConfiguration<ExampleEntity>
{
   public void Configure(EntityTypeBuilder<ExampleEntity> builder)
   {
      builder.Property(p => p.Id).ValueGeneratedNever();

      // more options here
   }
}

and i register them in my dbcontext like so

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);

  modelBuilder.ApplyConfiguration(new ExampleEntityConfiguration());

  // lot's more configurations here
}

has anyone come across or know of a way to register all the IEntityTypeConfiguration interfaces?

It just seems like a lot of repetitive code that could be solved by getting a list of the configurations, looping over them and applying in the context. I just don't know where to start with getting a list of IEntityTypeConfiguration classes that exist in a particular namespace.

Any help/suggestions would be great.

Body:
The nice work from @Evk kan be further encapsulated in a reusable extension method:

 public static class ModelBuilderExtensions
{
    public static void ApplyAllConfigurationsFromCurrentAssembly(this ModelBuilder modelBuilder, Assembly assembly, string configNamespace = "")
    {
        var applyGenericMethods = typeof(ModelBuilder).GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
        var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m=>m.GetParameters().FirstOrDefault().ParameterType.Name== "IEntityTypeConfiguration`1").FirstOrDefault();

        var applicableTypes = assembly
            .GetTypes()
            .Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters);

        if (!string.IsNullOrEmpty(configNamespace))
        {
            applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
        }

        foreach (var type in applicableTypes)
        {
            foreach (var iface in type.GetInterfaces())
            {
                // if type implements interface IEntityTypeConfiguration<SomeEntity>
                if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
                {
                    // make concrete ApplyConfiguration<SomeEntity> method
                    var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                    // and invoke that with fresh instance of your configuration type
                    applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
                    Console.WriteLine("applied model " + type.Name);
                    break;
                }
            }
        }
    }
}

And can be called as such:

public class ApiDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyAllConfigurationsFromCurrentAssembly("MyRoot.Api.Entities.Configuration");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }
}