How to use prefix tree data structure - r

I have a smg file that contains different articles. Now I would like to use prefix tree data structure to establish baseline word counts for the entire corpus of documents. A sample of the file can be found below:
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET"
OLDID="5544" NEWID="1">
<DATE>26-FEB-1987 15:01:01.79</DATE>
<TOPICS><D>cocoa</D></TOPICS>
<PLACES><D>el-salvador</D><D>usa</D><D>uruguay</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
C T
f0704reute
u f BC-BAHIA-COCOA-REVIEW 02-26 0105</UNKNOWN>
<TEXT>
<TITLE>BAHIA COCOA REVIEW</TITLE>
<DATELINE> SALVADOR, Feb 26 - </DATELINE><BODY>
Some text here.
Reuter
</BODY></TEXT>
</REUTERS>
Any advice on how to establish the baseline word counts?

use trie data structure to load strings and retrieve suggestions faster
public class Trie
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
c = c.ToString().ToUpper().ToCharArray().First();
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
public List<string> GetSuggestions(string word, int max)
{
List<string> outPut = new List<string>();
var node = Root;
int i = 0;
foreach (var l in word)
{
Node cNode;
if (node.Edges.TryGetValue(l, out cNode))
{
node = cNode;
}
else
{
if (i == word.Length - 1)
return outPut;
}
i++;
}
GetChildWords(node, ref outPut, max);
return outPut;
}
public void GetChildWords(Node n, ref List<string> outWords, int Max)
{
if (n.IsTerminal && outWords.Count < Max)
outWords.Add(n.Word);
foreach (var item in n.Edges)
{
GetChildWords(item.Value, ref outWords, Max);
}
}
}

Related

How do I periodically append to an array using the Arduino IDE?

I am trying to append float values that the user inputs through the serial monitor. I need these values stored in an array in a sequential fashion, i.e. each time I get a value, I must append it to the array.
Arduino doesn't come out of the box with dynamic data structures (except for String).
You can download open source implementations of generic containers from the web. Here's one: https://github.com/dhbikoff/Generic-C-Library/blob/master/vector.h
Also, here's a simple linked-list/vector I implemented myself as a toy project.
Be careful with dynamic memory. Memory fragmentation can cause your sketch to crash randomly (has happened to me several times).
template <typename T>
struct SimpleVector {
struct SimpleVectorNode {
T* m_value = NULL;
SimpleVectorNode* m_next = NULL;
SimpleVectorNode() {
}
SimpleVectorNode(T val) {
m_value = new T(val);
m_next = NULL;
}
};
int m_size = 0;
SimpleVectorNode* m_head = new SimpleVectorNode;
void AddValue(T val) {
++m_size;
SimpleVectorNode* end = m_head;
while (end->m_next != NULL) {
end = end->m_next;
}
end->m_next = new SimpleVectorNode(val);
}
SimpleVectorNode* Seek(int index) {
SimpleVectorNode* res = m_head;
while (index >= 0) {
--index;
res = res->m_next;
}
return res;
}
T& Get(int index) {
return *(Seek(index)->m_value);
}
void Delete(int index) {
SimpleVectorNode* preDel = Seek(index - 1);
SimpleVectorNode* toDel = preDel->m_next;
preDel->m_next = toDel->m_next;
delete toDel->m_value;
delete toDel;
--m_size;
}
int GetSize() {
return m_size;
}
int IndexOf(T val) {
SimpleVectorNode* pNode = m_head->m_next;
for (int i = 0; i < m_size; ++i) {
if (pNode->m_value == val) {
return i;
}
pNode = pNode->m_next;
}
return -1;
}
bool Contains(T val) {
return IndexOf(val) >= 0;
}
~SimpleVector() {
while (m_size > 0) {
Delete(0);
}
delete m_head;
}
};

Not all InvocationExpression are rewritten

I want to rewrite all InvocationExpression of "MyMethod" in a SyntaxTree to add a literal param 0 with
private class Rewriter : CSharpSyntaxRewriter
{
public int Id { get; set; }
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
var invokName = node.Expression.ToString();
if (invokName == "MyMethod")
{
var argus = node.ArgumentList.AddArguments(
SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(Id))));
return node.Update((ExpressionSyntax)Visit(node.Expression), argus);
}
return node;
}
}
static void Main(string[] args)
{
SyntaxTree oriTree = CSharpSyntaxTree.ParseText(#"
public class MyClass
{
public string MyMethod(int id)
{
return $""{id}"";
}
public void Say()
{
var tmp = MyMethod();//worked
var tmp1 = MyMethod();//worked
var tmp2 = ""Hi "" + MyMethod();//worked
Console.WriteLine($""Say {MyMethod()}"");//Not worked
Console.WriteLine(""Hello "" + MyMethod());//Not worked
}
}");
var syntaxRoot = oriTree.GetCompilationUnitRoot();
var visitor = new Rewriter();
visitor.Id = 0;
var changedSyntaxTree = visitor.Visit(syntaxRoot).SyntaxTree;
}
But not all are rewritten.
With
var methods = syntaxRoot.DescendantNodes().OfType<InvocationExpressionSyntax>().Where(o => o.Expression.ToString() == "MyMethod");
I can enumerate all InvocationExpression of "MyMethod". But I don't know how to change syntax tree without CSharpSyntaxRewriter.
How can I do it? Thanks.
It Solved based on CyrusNajmabadi's reply
you need to do this instead:
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
node = (InvocationExpressionSyntax)base.VisitInvocationExpression(node);
// now, the rest of your code:
var invokName = node.Expression.ToString();
// etc.
Thanks CyrusNajmabadi!

NullPointer for list within map

This is a homework assignment, so explanations and pointers are preferred to solutions. Our previous assignment was to create a Graph template using an adjacency-matrix. This homework assignment was to modify the previous one using an adjacency-list instead. I have the previous matrix based code commented out for reference.
import java.util.*;
public class Graph {
public Node rootNode;
public List<Node> nodes = new ArrayList<Node>();
Map<Integer, List<Integer>> adjList;
//public int[][] adjMatrix;
int size;
public void setRootNode(Node n) {
rootNode = n;
}
public Node getRootNode() {
return rootNode;
}
public void addNode(Node n) {
nodes.add(n);
}
// This method will be called to make connect two nodes
public void connectNode(Node src, Node dst) {
// if (adjMatrix == null)
// {
// size = nodes.size();
// adjMatrix = new int[size][size];
// }
int srcIndex = nodes.indexOf(src);
int dstIndex = nodes.indexOf(dst);
// adjMatrix[srcIndex][dstIndex] = 1;
// adjMatrix[dstIndex][srcIndex] = 1;
if (!adjList.containsKey(srcIndex))
adjList.put(srcIndex, new ArrayList<Integer>());
adjList.get(srcIndex).add(dstIndex);
if (!adjList.containsKey(dstIndex))
adjList.put(dstIndex, new ArrayList<Integer>());
adjList.get(dstIndex).add(srcIndex);
}
private Node getUnvisitedChildNode(Node n) {
int index = nodes.indexOf(n);
for (int j = 0; j < size; j++)
//if (adjMatrix[index][j] == 1 && ((Node) nodes.get(j)).visited == false)
if (adjList.containsKey(index) && ((Node) nodes.get(j)).visited == false)
return nodes.get(j);
return null;
}
// BFS traversal: iterative version
public void bfs() {
// BFS uses a Queue data structure
Queue<Node> q = new LinkedList<Node>();
q.add(rootNode);
printNode(rootNode);
rootNode.visited = true;
while (!q.isEmpty()) {
Node n = q.remove();
Node child = null;
while ((child = getUnvisitedChildNode(n)) != null) {
child.visited = true;
printNode(child);
q.add(child);
}
}
}
// DFS traversal: iterative version
public void dfs() {
// DFS uses a Stack data structure
Stack<Node> s = new Stack<Node>();
s.push(rootNode);
rootNode.visited = true;
printNode(rootNode);
while (!s.isEmpty()) {
Node n = s.peek();
Node child = getUnvisitedChildNode(n);
if (child != null) {
child.visited = true;
printNode(child);
s.push(child);
} else
s.pop();
}
}
// Utility methods for clearing visited property of node
private void reset() {
for (Node n : nodes)
n.visited = false;
}
// Utility methods for printing the node's label
private void printNode(Node n) {
System.out.print(n.label + " ");
}
// get all neighboring nodes of node n.
public List<Node> getNeighbors(Node n) {
int srcIndex = nodes.indexOf(n);
List<Node> neighbors = new ArrayList<Node>();
// for (int j = 0; j < adjMatrix[srcIndex].length; j++)
// if (adjMatrix[srcIndex][j] == 1)
for (int j = 0; j < adjList.get(srcIndex).size(); j++)
if (adjList.get(srcIndex).contains(j))
neighbors.add(nodes.get(j));
return neighbors;
}
// implement recursive version of dfs
public void dfs(Node n) {
printNode(n); // visit the node
n.visited = true;
for (Node node : getNeighbors(n))
if (!node.visited)
dfs(node);
}
static class Node {
public char label;
public boolean visited = false;
public Node(char label) {
this.label = label;
}
}
public static void main(String[] args) {
// Lets create nodes as given as an example in the article
Node n0 = new Node('0');
Node n1 = new Node('1');
Node n2 = new Node('2');
Node n3 = new Node('3');
Node n4 = new Node('4');
Node n5 = new Node('5');
Node n6 = new Node('6');
Node n7 = new Node('7');
Node n8 = new Node('8');
// Create the graph, add nodes, create edges between nodes
Graph g = new Graph();
g.addNode(n0);
g.addNode(n1);
g.addNode(n2);
g.addNode(n3);
g.addNode(n4);
g.addNode(n5);
g.addNode(n6);
g.addNode(n7);
g.addNode(n8);
g.setRootNode(n8);
g.connectNode(n0, n1);
g.connectNode(n0, n3);
g.connectNode(n0, n8);
g.connectNode(n1, n7);
g.connectNode(n3, n2);
g.connectNode(n3, n4);
g.connectNode(n3, n4);
g.connectNode(n4, n8);
g.connectNode(n2, n7);
g.connectNode(n2, n5);
g.connectNode(n5, n6);
// Perform the DFS and BFS traversal of the graph
// System.out.print("DFS Traversal (Iterative): ");
// g.dfs();
// g.reset();
System.out.print("\nDFS Traversal (Recursive): ");
g.dfs(g.getRootNode());
g.reset();
System.out.print("\nBFS Traversal (Iterative): ");
g.bfs();
g.reset();
}
}
I'm getting a Null pointer in the connectNode method where I bring in the ArrayList. Again please keep in mind this is homework. Thank you in advance for all your help.
edit: How do you get line numbers to appear within stackoverflow?
if (!adjList.containsKey(srcIndex)) your adjList is null. You never set this List in your object.

Create Multimedia component with Metadata fields.using core service

I am creating Multimedia components using core service and everything is working fine. But when Metadata schema fields are defined on the Multimedia schema using which I am creating my Multimedia components then I am getting following error:-
Unable to find http://www.tridion.com/ContentManager/5.0/DefaultMultimediaSchema:Metadata.
This message is displayed when I have given Default Multimedia schema's TCM ID for Multimedia component. As metadata fields are saved in Tridion Database so I first have to retrieve these fields from broker or what is the best solution for this, please suggest. Below is the sample code. Please modify it if someone have any idea for providing default value for metadatafields and how to retrieve them (with/without querying broker DB):-
public static string UploadMultiMediaComponent(string folderUri, string title, string schemaID)
{
core_service.ServiceReference1.SessionAwareCoreService2010Client client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword"; client.Open();
ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(
ItemType.Component, folderUri);
multimediaComponent.Title = title;
multimediaComponent.ComponentType = ComponentType.Multimedia;
multimediaComponent.Schema.IdRef =schemaID;
//multimediaComponent.Metadata = "";
StreamUpload2010Client streamClient = new StreamUpload2010Client();
FileStream objfilestream = new FileStream(#"\My Documents\images.jpg",
FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg",
objfilestream);
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
binaryContent.Filename = "images.jpg";
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
// for jpg file
IdRef = "tcm:0-2-65544"
};
multimediaComponent.BinaryContent = binaryContent;
IdentifiableObjectData savedComponent = client.Save(multimediaComponent,
new ReadOptions());
client.CheckIn(savedComponent.Id, null);
streamClient.Close();
client.Close();
Console.WriteLine(savedComponent.Id);
//}
}
I don't know why your code not working but following code is working for me
public static ComponentData GenerateMultiMediaComponent(TridionGeneration tridionGeneration, XmlData newsArticle, string componentName)
{
try
{
Dictionary<string, object> dicTridion = Common.GetTridionObject(tridionGeneration.client, ItemType.Component, tridionGeneration.Settings.ComponentFolderUri, componentName);
int objectCount = (int)dicTridion["count"];
SchemaFieldsData schemaFields = tridionGeneration.client.ReadSchemaFields(tridionGeneration.Settings.SchemaUri, true, new ReadOptions());
ComponentData componentData = (ComponentData)tridionGeneration.client.GetDefaultData(ItemType.Component, tridionGeneration.Settings.ComponentFolderUri);
if (schemaFields.Fields != null)
{
var fields = Fields.ForContentOf(schemaFields);
Helper.FillSchemaFields(tridionGeneration, fields);
componentData.Content = fields.ToString();
}
if (schemaFields.MetadataFields != null)
{
var metafields = Fields.ForMetadataOf(schemaFields, componentData);
Helper.FillSchemaFields(tridionGeneration, metafields);
componentData.Metadata = metafields.ToString();
}
componentData.Title = (objectCount == 0) ? componentName : componentName + " " + (objectCount + 1).ToString();
componentData.ComponentType = ComponentType.Multimedia;
StreamUpload2010Client streamClient = new StreamUpload2010Client();
FileStream objfilestream = new FileStream(#"[IMAGE_PATH]", FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg", objfilestream);
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
binaryContent.Filename = "[IMAGE_NAME]";
componentData.BinaryContent = binaryContent;
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
IdRef = "tcm:0-2-65544"
};
componentData = (ComponentData)tridionGeneration.client.Create(componentData, new ReadOptions());
return componentData;
}
catch (Exception ex)
{
return null;
}
}
Here is the Helper class:
public static class Helper
{
public static void FillSchemaFields(TridionGeneration tridionGeneration, Fields fields)
{
List<XmlData> data = XmlHelper.xmlData;
var ofield = fields.GetEnumerator();
while (ofield.MoveNext())
{
Field f = ofield.Current;
FillFieldValue(tridionGeneration, fields, f, data[0]);
}
}
private static void FillFieldValue(TridionGeneration tridionGeneration, Fields fields, Field f, XmlData data)
{
if (f.Type == typeof(MultimediaLinkFieldDefinitionData))
{
fields[f.Name].Value = tridionGeneration.Settings.DefaultImageUri;
}
else if (f.Type != typeof(EmbeddedSchemaFieldDefinitionData))
{
foreach (XmlData fieldvalue in data.Attributes)
{
if (f.Type == typeof(DateFieldDefinitionData))
{
if (fieldvalue.text.ToLower() == f.Name.ToLower())
{
fields[f.Name].Value = Convert.ToDateTime(fieldvalue.value).ToString("yyyy-MM-ddTHH:mm:ss");
}
else
{
string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
if (!string.IsNullOrEmpty(val))
{
fields[f.Name].Value = Convert.ToDateTime(val).ToString("yyyy-MM-ddTHH:mm:ss");
}
}
}
else
{
if (fieldvalue.text.ToLower() == f.Name.ToLower())
{
fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(fieldvalue.value);
}
else
{
string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
if (!string.IsNullOrEmpty(val))
{
fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(val);
}
}
}
}
}
else
{
Fields fs = f.GetSubFields();
var ofield = fs.GetEnumerator();
while (ofield.MoveNext())
{
Field ff = ofield.Current;
FillFieldValue(tridionGeneration, fs, ff, data);
}
}
}
private static string FindSchemaValue(TridionGeneration tridionGeneration, List<XmlData> data, string fieldname)
{
foreach (XmlData fieldvalue in data)
{
if (fieldvalue.text.ToLower() == fieldname.ToLower())
{
return fieldvalue.value;
}
else
{
FindSchemaValue(tridionGeneration, fieldvalue.Attributes, fieldname);
}
}
return "";
}
}
and the Fields class:
public class Fields
{
private ItemFieldDefinitionData[] definitions;
private XmlNamespaceManager namespaceManager;
private XmlElement root; // the root element under which these fields live
// at any point EITHER data OR parent has a value
private SchemaFieldsData data; // the schema fields data as retrieved from the core service
private Fields parent; // the parent fields (so we're an embedded schema), where we can find the data
public Fields(SchemaFieldsData _data, ItemFieldDefinitionData[] _definitions, string _content = null, string _rootElementName = null)
{
data = _data;
definitions = _definitions;
var content = new XmlDocument();
if (!string.IsNullOrEmpty(_content))
{
content.LoadXml(_content);
}
else
{
content.AppendChild(content.CreateElement(string.IsNullOrEmpty(_rootElementName) ? _data.RootElementName : _rootElementName, _data.NamespaceUri));
}
root = content.DocumentElement;
namespaceManager = new XmlNamespaceManager(content.NameTable);
namespaceManager.AddNamespace("custom", _data.NamespaceUri);
}
public Fields(Fields _parent, ItemFieldDefinitionData[] _definitions, XmlElement _root)
{
definitions = _definitions;
parent = _parent;
root = _root;
}
public static Fields ForContentOf(SchemaFieldsData _data)
{
return new Fields(_data, _data.Fields);
}
public static Fields ForContentOf(SchemaFieldsData _data, ComponentData _component)
{
return new Fields(_data, _data.Fields, _component.Content);
}
public static Fields ForMetadataOf(SchemaFieldsData _data, RepositoryLocalObjectData _item)
{
return new Fields(_data, _data.MetadataFields, _item.Metadata, "Metadata");
}
public string NamespaceUri
{
get { return data != null ? data.NamespaceUri : parent.NamespaceUri; }
}
public XmlNamespaceManager NamespaceManager
{
get { return parent != null ? parent.namespaceManager : namespaceManager; }
}
internal IEnumerable<XmlElement> GetFieldElements(ItemFieldDefinitionData definition)
{
return root.SelectNodes("custom:" + definition.Name, NamespaceManager).OfType<XmlElement>();
}
internal XmlElement AddFieldElement(ItemFieldDefinitionData definition)
{
var newElement = root.OwnerDocument.CreateElement(definition.Name, NamespaceUri);
XmlNodeList nodes = root.SelectNodes("custom:" + definition.Name, NamespaceManager);
XmlElement referenceElement = null;
if (nodes.Count > 0)
{
referenceElement = (XmlElement)nodes[nodes.Count - 1];
}
else
{
// this is the first value for this field, find its position in the XML based on the field order in the schema
bool foundUs = false;
for (int i = definitions.Length - 1; i >= 0; i--)
{
if (!foundUs)
{
if (definitions[i].Name == definition.Name)
{
foundUs = true;
}
}
else
{
var values = GetFieldElements(definitions[i]);
if (values.Count() > 0)
{
referenceElement = values.Last();
break; // from for loop
}
}
} // for every definition in reverse order
} // no existing values found
root.InsertAfter(newElement, referenceElement); // if referenceElement is null, will insert as first child
return newElement;
}
public IEnumerator<Field> GetEnumerator()
{
return (IEnumerator<Field>)new FieldEnumerator(this, definitions);
}
public Field this[string _name]
{
get
{
var definition = definitions.First<ItemFieldDefinitionData>(ifdd => ifdd.Name == _name);
if (definition == null) throw new ArgumentOutOfRangeException("Unknown field '" + _name + "'");
return new Field(this, definition);
}
}
public override string ToString()
{
return root.OuterXml;
}
}
public class FieldEnumerator : IEnumerator<Field>
{
private Fields fields;
private ItemFieldDefinitionData[] definitions;
// Enumerators are positioned before the first element until the first MoveNext() call
int position = -1;
public FieldEnumerator(Fields _fields, ItemFieldDefinitionData[] _definitions)
{
fields = _fields;
definitions = _definitions;
}
public bool MoveNext()
{
position++;
return (position < definitions.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Field Current
{
get
{
try
{
return new Field(fields, definitions[position]);
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public void Dispose()
{
}
}
public class Field
{
private Fields fields;
private ItemFieldDefinitionData definition;
public Field(Fields _fields, ItemFieldDefinitionData _definition)
{
fields = _fields;
definition = _definition;
}
public string Name
{
get { return definition.Name; }
}
public Type Type
{
get { return definition.GetType(); }
}
public string Value
{
get
{
return Values.Count > 0 ? Values[0] : null;
}
set
{
if (Values.Count == 0) fields.AddFieldElement(definition);
Values[0] = value;
}
}
public ValueCollection Values
{
get
{
return new ValueCollection(fields, definition);
}
}
public void AddValue(string value = null)
{
XmlElement newElement = fields.AddFieldElement(definition);
if (value != null) newElement.InnerText = value;
}
public void RemoveValue(string value)
{
var elements = fields.GetFieldElements(definition);
foreach (var element in elements)
{
if (element.InnerText == value)
{
element.ParentNode.RemoveChild(element);
}
}
}
public void RemoveValue(int i)
{
var elements = fields.GetFieldElements(definition).ToArray();
elements[i].ParentNode.RemoveChild(elements[i]);
}
public IEnumerable<Fields> SubFields
{
get
{
var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
if (embeddedFieldDefinition != null)
{
var elements = fields.GetFieldElements(definition);
foreach (var element in elements)
{
yield return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, (XmlElement)element);
}
}
}
}
public Fields GetSubFields(int i = 0)
{
var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
if (embeddedFieldDefinition != null)
{
var elements = fields.GetFieldElements(definition);
if (i == 0 && !elements.Any())
{
// you can always set the first value of any field without calling AddValue, so same applies to embedded fields
AddValue();
elements = fields.GetFieldElements(definition);
}
return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, elements.ToArray()[i]);
}
else
{
throw new InvalidOperationException("You can only GetSubField on an EmbeddedSchemaField");
}
}
// The subfield with the given name of this field
public Field this[string name]
{
get { return GetSubFields()[name]; }
}
// The subfields of the given value of this field
public Fields this[int i]
{
get { return GetSubFields(i); }
}
}
Can you try this?
multimediaComponent.Metadata = "<Metadata/>";

Use MatchPattern property of FindMatchingFiles workflow activity

I'm customizing the default workflow of build process template using TFS 2010 Team Build. There is an activity named FindMatchingFiles allows to search for specific files with a pattern defined in MatchPattern property. It works if I only specify one file extension. Example:
String.Format("{0}\\**\\\*.msi", SourcesDirectory)
But I would like to include *.exe as well. Trying following pattern but it doesn't work:
String.Format("{0}\\**\\\*.(msi|exe)", SourcesDirectory)
Anyone could show me how to correct it?
You can use String.Format("{0}\**\*.msi;{0}\**\*.exe", SourcesDirectory)
The FindMatchingFiles activity's MatchPattern property uses the
Syntax that is supported by the searchPattern argument of the Directory.GetFiles(String, String) method.
That means that you can't combine multiple extensions. You'll need to call the FindMatchingFiles activity twice. You can then combine the results of those two calls when you use them (i.e. if your results are msiFiles and exeFiles, you can use msiFiles.Concat(exeFiles) as the input to a ForEach).
However, as you can see with #antwoord's answer, the activity does actually seem to accept a semi-colon delimited list of patterns, unlike Directory.GetFiles.
FindMatchingFiles has some strange search pattern. Here is the code (decompiled using ILSpy) so you can test your search patterns without having to kick off a new build.
It contains a hardcoded root dir at the following location (Z:)
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
Code:
using System;
using System.Collections.Generic;
using System.IO;
namespace DirectoryGetFiles
{
//// Use the FindMatchingFiles activity to find files. Specify the search criteria in the MatchPattern (String) property.
//// In this property, you can specify an argument that includes the following elements:
//// Syntax that is supported by the searchPattern argument of the Directory GetFiles(String, String) method.
////
//// ** to specify a recursive search. For example:
//// To search the sources directory for text files, you could specify something that resembles the following
//// value for the MatchPattern property: String.Format("{0}\**\*.txt", SourcesDirectory).
////
//// To search the sources directory for text files in one or more subdirectories that are called txtfiles,
//// you could specify something that resembles the following value for the MatchPattern property:
//// String.Format("{0}\**\txtfiles\*.txt", SourcesDirectory).
class Program
{
static void Main(string[] args)
{
string searchPattern = #"_PublishedWebsites\Web\Scripts\jasmine-specs**\*.js";
var results = Execute(searchPattern);
foreach (var i in results)
{
Console.WriteLine("found: {0}", i);
}
Console.WriteLine("Done...");
Console.ReadLine();
}
private static IEnumerable<string> Execute(string pattern)
{
string text = pattern;
text = text.Replace(";;", "\0");
var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] array = text.Split(new char[]
{
';'
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
string text3 = text2.Replace("\0", ";");
if (IsValidPattern(text3))
{
List<string> list = ComputeMatchingPaths(text3);
if (list.Count > 0)
{
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
hashSet.Add(current);
}
goto IL_15C;
}
}
////Message = ActivitiesResources.Format("NoMatchesForSearchPattern", new object[]
}
else
{
//// Message = ActivitiesResources.Format("InvalidSearchPattern", new object[]
}
IL_15C: ;
}
return hashSet;//.OrderBy((string x) => x, FileSpec.TopDownComparer);
}
private static bool IsValidPattern(string pattern)
{
string text = "**" + Path.DirectorySeparatorChar;
int num = pattern.IndexOf(text, StringComparison.Ordinal);
return (num < 0 || (pattern.IndexOf(text, num + text.Length, StringComparison.OrdinalIgnoreCase) <= 0 && pattern.IndexOf(Path.DirectorySeparatorChar, num + text.Length) <= 0)) && pattern[pattern.Length - 1] != Path.DirectorySeparatorChar;
}
private static List<string> ComputeMatchingPaths(string matchPattern)
{
List<string> list = new List<string>();
string text = "**" + Path.DirectorySeparatorChar;
int num = matchPattern.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase);
if (num >= 0)
{
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
string searchPattern = matchPattern.Substring(num + text.Length);
using (List<string>.Enumerator enumerator = matchingDirectories.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
list.AddRange(Directory.GetFiles(current, searchPattern, SearchOption.AllDirectories));
}
return list;
}
}
int num2 = matchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (num2 >= 0)
{
List<string> matchingDirectories2 = GetMatchingDirectories(string.Empty, matchPattern.Substring(0, num2 + 1), 0);
string searchPattern2 = matchPattern.Substring(num2 + 1);
using (List<string>.Enumerator enumerator2 = matchingDirectories2.GetEnumerator())
{
while (enumerator2.MoveNext())
{
string current2 = enumerator2.Current;
try
{
list.AddRange(Directory.GetFiles(current2, searchPattern2, SearchOption.TopDirectoryOnly));
}
catch
{
}
}
return list;
}
}
try
{
list.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), matchPattern, SearchOption.TopDirectoryOnly));
}
catch
{
}
return list;
}
private static List<string> GetMatchingDirectories(string rootDir, string pattern, int level)
{
if (level > 129)
{
return new List<string>();
}
List<string> list = new List<string>();
int num = pattern.IndexOf('*');
if (num >= 0)
{
int num2 = pattern.Substring(0, num).LastIndexOf(Path.DirectorySeparatorChar);
string text = (num2 >= 0) ? Path.Combine(rootDir, pattern.Substring(0, num2 + 1)) : rootDir;
if (text.Equals(string.Empty))
{
text = Directory.GetCurrentDirectory();
}
int num3 = pattern.IndexOf(Path.DirectorySeparatorChar, num);
if (num3 < 0)
{
num3 = pattern.Length;
}
string searchPattern = pattern.Substring(num2 + 1, num3 - num2 - 1);
try
{
string[] directories = Directory.GetDirectories(text, searchPattern, SearchOption.TopDirectoryOnly);
if (num3 < pattern.Length - 1)
{
string pattern2 = pattern.Substring(num3 + 1);
string[] array = directories;
for (int i = 0; i < array.Length; i++)
{
string rootDir2 = array[i];
list.AddRange(GetMatchingDirectories(rootDir2, pattern2, level + 1));
}
}
else
{
list.AddRange(directories);
}
return list;
}
catch
{
return list;
}
}
string text2 = Path.Combine(rootDir, pattern);
if (text2.Equals(string.Empty))
{
list.Add(Directory.GetCurrentDirectory());
}
else
{
if (Directory.Exists(text2))
{
list.Add(Path.GetFullPath(text2));
}
}
return list;
}
}
}

Resources