本文整理汇总了C#中SortedList.ElementAt方法的典型用法代码示例。如果您正苦于以下问题:C# SortedList.ElementAt方法的具体用法?C# SortedList.ElementAt怎么用?C# SortedList.ElementAt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedList
的用法示例。
在下文中一共展示了SortedList.ElementAt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestMethod
public void TestMethod(int maxOpsCount, int repeatTimes)
{
Repeat(repeatTimes, () => {
var opsCount = Random.Next(maxOpsCount + 1);
var list = new SortedList<Tuple<double, int>, object>(new Comparer());
var finder = new MedianFinder();
for (var i = 0; i < opsCount; ++i)
{
if (i == 0 || Random.Next(2) == 0)
{
double newValue = Random.Next(100);
//System.Console.WriteLine("Add: " + newValue);
list.Add(Tuple.Create(newValue, i), null);
finder.AddNum(newValue);
}
else
{
double expectedMedian;
if (list.Count % 2 == 0)
{
var x = new SortedList<object, object>();
expectedMedian = (list.ElementAt(list.Count / 2 - 1).Key.Item1 + list.ElementAt(list.Count / 2).Key.Item1) / 2;
}
else
{
expectedMedian = list.ElementAt(list.Count / 2).Key.Item1;
}
if (expectedMedian != finder.FindMedian())
{
Assert.AreEqual(expectedMedian, finder.FindMedian(), JsonConvert.SerializeObject(list.Keys.Select(k => k.Item1)));
}
}
}
});
}
示例2: ExecuteTask
public override void ExecuteTask()
{
if (File.Exists(this.namesFile))
{
SortedList<string, int> names = new SortedList<string, int>();
string[] splitNames = File.ReadAllText(this.namesFile).Split(',');
foreach(string rawName in splitNames)
{
string name = rawName.Trim('"').ToUpper();
int sum = 0;
foreach (char index in name )
{
sum += (Convert.ToInt32(index) - 64);
}
names.Add(name, sum);
}
long total = 0;
int length = names.Count;
for (int place = 1; place <= length; place++)
{
total += place * (names.ElementAt(place - 1).Value);
}
this.Result = "" + total;
return;
}
this.Result = "-";
}
示例3: Write
public string Write(SortedList<DateTime, dynamic> inList, string separator)
{
StringBuilder outputString = new StringBuilder();
float value;
string type = "";
DateTime date;
if (inList!=null && inList.Count>0)
{
var kvp = inList.ElementAt(0);
string fieldValue = "";
if (kvp.Value!=null)
fieldValue = kvp.Value.ToString();
if (float.TryParse(fieldValue, out value))
type = ",float";
else if (DateTime.TryParse(fieldValue, out date))
{
type = ",date";
}
else
type = ",string";
}
foreach (var kvp in inList)
{
outputString.Append(kvp.Key.ToString(format: "yyyy/MM/dd"));
outputString.Append(separator);
string fieldValue = "";
if (kvp.Value != null)
if (typeof(DateTime) == kvp.Value.GetType())
{
fieldValue = kvp.Value.ToString(format: "yyyy/MM/dd");
}
else
fieldValue = kvp.Value.ToString();
outputString.Append(fieldValue);
outputString.AppendLine(type);
}
return outputString.ToString();
}
示例4: FindPath
void FindPath(Node start, Node end)
{
foreach(Node node in nodes)
{
node.Reset();
}
SortedList<float, List<Node>> openList = new SortedList<float, List<Node>>();
start.cost = 0;
start.heuristic = (end.position - start.position).magnitude;
start.total = start.cost + start.heuristic;
start.status = Node.NodeStatus.Open;
AddNode(openList, start);
while(openList.Count > 0)
{
Node current = openList.ElementAt(0).Value[0];
RemoveNode(openList, current);
current.status = Node.NodeStatus.Closed;
if(current == end)
break;
foreach(Node node in current.neighbors)
{
if(node.status == Node.NodeStatus.Closed)
continue;
float tempCost = current.cost + (current.position - node.position).magnitude;
if(tempCost < node.cost)
{
if(node.status == Node.NodeStatus.Open)
RemoveNode (openList,node);
node.cost = tempCost;
node.heuristic = (end.position - node.position).magnitude;
node.total = node.cost + node.heuristic;
node.parent = current;
AddNode (openList,node);
node.status = Node.NodeStatus.Open;
}
}
}
}
示例5: Search
public void Search()
{
foreach (AStarNode node in Nodes)
{
node.Closed = false;
}
OpenList = new SortedList<float, List<AStarNode>>();
Start.Cost = 0;
AddToOpenList(Start, null, End);
while (OpenList.Count > 0)
{
AStarNode current = OpenList.ElementAt(0).Value[0];
OpenList.ElementAt(0).Value.Remove(current);
if (OpenList.ElementAt(0).Value.Count == 0)
{
OpenList.RemoveAt(0);
}
if (current == End)
{
return; // done!
}
if (current.Row < Rows - 1 && !Nodes[current.Row + 1, current.Col].Closed)
{
AddToOpenList(Nodes[current.Row + 1, current.Col], current, End);
}
if (current.Col < Cols - 1 && !Nodes[current.Row, current.Col + 1].Closed)
{
AddToOpenList(Nodes[current.Row, current.Col + 1], current, End);
}
if (current.Row > 0 && !Nodes[current.Row - 1, current.Col].Closed)
{
AddToOpenList(Nodes[current.Row - 1, current.Col], current, End);
}
if (current.Col > 0 && !Nodes[current.Row, current.Col - 1].Closed)
{
AddToOpenList(Nodes[current.Row, current.Col - 1], current, End);
}
}
}
示例6: GreadyChange
private bool GreadyChange(int change, ref SortedList<int, int> availableAmounts, ref LinkedList<int> changeAmounts)
{
if (change == 0) return true;
bool possible = false;
for (int i = 0; i < availableAmounts.Count; i++)
{
KeyValuePair<int, int> curAmout = availableAmounts.ElementAt(i);
if (curAmout.Value > 0)
{
if (change - curAmout.Key >= 0)
{
availableAmounts[curAmout.Key]--;
changeAmounts.AddLast(curAmout.Key);
if (GreadyChange(change - curAmout.Key, ref availableAmounts, ref changeAmounts))
{
possible = true;
break;
}
else
{
changeAmounts.RemoveLast();
availableAmounts[curAmout.Key]++;
}
}
}
}
if (possible) return true;
else return false;
}
示例7: Write_SQL_Inserts
//.........这里部分代码省略.........
if (portalHash.ContainsKey(code.ToUpper()))
{
int portalid = portalHash[code.ToUpper()];
sqlWriter.WriteLine(
"insert into SobekCM_Portal_URL_Statistics ( PortalID, [Year], [Month], [Hits] ) values ( " +
portalid + ", " + year + ", " + month + ", " + portalRow[1] + " );");
}
}
sqlWriter.WriteLine("GO");
sqlWriter.WriteLine();
}
// Add the item aggregation stats (non-institutional)
SortedList<int, string> sql = new SortedList<int, string>();
foreach (DataRow hierarchyRow in collection_stats.Rows)
{
string code = hierarchyRow["code"].ToString().ToUpper();
if (aggregationHash.ContainsKey(code))
{
int hits = Convert.ToInt32(hierarchyRow["home_page_hits"]) +
Convert.ToInt32(hierarchyRow["browse_hits"]) +
Convert.ToInt32(hierarchyRow["advanced_search_hits"]) +
Convert.ToInt32(hierarchyRow["results_hits"]);
sql.Add(aggregationHash[code],
"insert into SobekCM_Item_Aggregation_Statistics ( AggregationID, [Year], [Month], [Hits], [Sessions], Home_Page_Views, Browse_Views, Advanced_Search_Views, Search_Results_Views ) values ( " +
aggregationHash[code] + ", " + year + ", " + month + ", " + hits + ", " +
hierarchyRow["sessions"] + ", " + hierarchyRow["home_page_hits"] + ", " +
hierarchyRow["browse_hits"] + ", " + hierarchyRow["advanced_search_hits"] + ", " +
hierarchyRow["results_hits"] + ");");
}
}
for (int i = 0; i < sql.Count; i++)
sqlWriter.WriteLine(sql.ElementAt(i).Value);
sqlWriter.WriteLine("GO");
sqlWriter.WriteLine();
foreach (DataRow hierarchyRow in institution_stats.Rows)
{
string code = hierarchyRow["code"].ToString().ToUpper();
if (aggregationHash.ContainsKey(code))
{
int hits = Convert.ToInt32(hierarchyRow["home_page_hits"]) +
Convert.ToInt32(hierarchyRow["browse_hits"]) +
Convert.ToInt32(hierarchyRow["advanced_search_hits"]) +
Convert.ToInt32(hierarchyRow["results_hits"]);
sqlWriter.WriteLine(
"insert into SobekCM_Item_Aggregation_Statistics ( AggregationID, [Year], [Month], [Hits], [Sessions], Home_Page_Views, Browse_Views, Advanced_Search_Views, Search_Results_Views ) values ( " +
aggregationHash[code] + ", " + year + ", " + month + ", " + hits + ", " +
hierarchyRow["sessions"] + ", " + hierarchyRow["home_page_hits"] + ", " +
hierarchyRow["browse_hits"] + ", " + hierarchyRow["advanced_search_hits"] + ", " +
hierarchyRow["results_hits"] + ");");
}
}
sqlWriter.WriteLine("GO");
sqlWriter.WriteLine();
foreach (DataRow hierarchyRow in bib_stats.Rows)
{
if (bibHash.ContainsKey(hierarchyRow["bibid"].ToString().ToUpper()))
{
sqlWriter.WriteLine(
"insert into SobekCM_Item_Group_Statistics ( GroupID, [Year], [Month], [Hits], [Sessions] ) values ( " +
bibHash[hierarchyRow["bibid"].ToString()] + ", " + year + ", " + month + ", " +
hierarchyRow["hits"] + ", " + hierarchyRow["sessions"] + " );");
示例8: RayIntersect
public int RayIntersect( float ox, float oy, float dx, float dy, int k, int[] result )
{
// !!!{{ TODO: add the intersection code here
if ( segs == null || k <= 0 ) return 0;
SortedList<double, int> res = new SortedList<double, int>();
for ( int i = 0; i < segs.Count; i++ )
{
Segment2D seg = segs[ i ];
double dist = RaySegment2D( ox, oy, dx, dy, seg.x1, seg.y1, seg.x2, seg.y2 );
segmentCounter++;
if ( dist >= 0.0 )
res.Add( dist, i );
}
int n = Math.Min( k, res.Count );
for ( int i = 0; i < n; i++ )
result[ i ] = res.ElementAt( i ).Value;
return n;
// !!!}}
}
示例9: FindBestBoundingBox
/// <summary>
/// If no bounding box is found, returns the last bounding box.
/// </summary>
/// <returns></returns>
List<Rectangle> FindBestBoundingBox(short[] depthFrame, Skeleton skeleton)
{
CvInvoke.cvConvert(SaliencyProb.Ptr, TempMask.Ptr);
// Non-zero pixels are treated as 1s. Source image content is modifield.
CvInvoke.cvFindContours(TempMask.Ptr, storage, ref contourPtr, StructSize.MCvContour,
RETR_TYPE.CV_RETR_EXTERNAL, CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, new Point(0, 0));
var contour = new Seq<Point>(contourPtr, null);
SortedList<float, Seq<Point>> bestContours = new SortedList<float, Seq<Point>>();
List<Rectangle> bestBoundingBoxes = new List<Rectangle>();
float z = DefaultZDist;
var hand = SkeletonUtil.GetJoint(skeleton, JointType.HandRight);
if (hand != null)
z = hand.Position.Z;
double perimThresh = DepthUtil.GetDepthImageLength(width, HandWidth, z) * 2;
FaceModel = SkeletonUtil.GetFaceModel(skeleton, mapper);
for (; contour != null && contour.Ptr.ToInt32() != 0; contour = contour.HNext) {
var perim = CvInvoke.cvContourPerimeter(contour.Ptr);
if (perim > perimThresh) {
var rect = contour.BoundingRectangle;
var score = ContourScore(rect);
var center = rect.Center();
int x = (int)center.X;
int y = (int)center.Y;
var depth = DepthUtil.RawToDepth(depthFrame[y * width + x]);
if (!FaceModel.IsPartOfFace(x, y, depth) &&
(bestContours.Count < NumTrackedHands || score > bestContours.ElementAt(0).Key)) {
bestContours.Add(score, contour);
if (bestContours.Count > NumTrackedHands)
bestContours.RemoveAt(0);
}
}
}
if (bestContours.Count > 0) {
foreach (var c in bestContours.Values) {
var rect = c.BoundingRectangle;
CvInvoke.cvCamShift(TrackedDepthFrame.Ptr, rect, new MCvTermCriteria(CamShiftIter),
out connectedComp, out shiftedBox);
var bestBoundingBox = shiftedBox.MinAreaRect();
bestBoundingBoxes.Add(bestBoundingBox);
//FloodFill(TrackedDepthFrame, bestBoundingBox);
//if (bestBoundingBox.Width > 0) {
// TempMask.ROI = bestBoundingBox;
// CvInvoke.cvFindContours(TempMask.Ptr, storage, ref contourPtr, StructSize.MCvContour,
// RETR_TYPE.CV_RETR_EXTERNAL, CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
// new Point(0, 0));
// contour = new Seq<Point>(contourPtr, null);
// Seq<Point> largestContour = null;
// var maxPerim = perimThresh;
// for (; contour != null && contour.Ptr.ToInt32() != 0; contour = contour.HNext) {
// var perim = CvInvoke.cvContourPerimeter(contour.Ptr);
// if (perim > maxPerim) {
// maxPerim = perim;
// largestContour = contour;
// }
// }
// CvInvoke.cvZero(TempMask.Ptr);
// if (largestContour != null)
// TempMask.Draw(largestContour, new Gray(255), -1);
// FilterImage(TrackedDepthFrame, TempMask);
// TempMask.ROI = Rectangle.Empty;
//}
}
}
return bestBoundingBoxes;
}
示例10: Start
//.........这里部分代码省略.........
//if the new platform is still overlapping, do not place it - decrement the iteration number to try again from a new platform to reach from
if (is_overlapping)
--a;
//otherwise, place the platform
else{
all_platforms.Add(platform);
right_extremities.Add(platform.get_right_extremity(), a);
left_extremities.Add(platform.get_left_extremity(), a);
upper_extremities.Add(platform.get_upper_extremity(), a);
lower_extremities.Add(platform.get_lower_extremity(), a);
}
}
//construct a directed graph with edges between plaforms that are sufficiently reachable from each other
//build_graph_edges();
//check if the graph represents a level which can be traversed based on the mobility of the player
//UPDATE THIS TO CORRECT THE GRAPH WHEN IT IS NOT VALID
//ADD THE CORRECT INDICATION OF THE START AND END NODES
//if (!platform_graph.isValid(0, 1))
//print ("LEVEL CANNOT BE COMPLETED BY CURRENT PLAYER");
right_extremity_cutoff = player.localPosition.x - X_RECYLE_CUTOFF;
left_extremity_cutoff = player.localPosition.x + X_RECYLE_CUTOFF;
upper_extremity_cutoff = player.localPosition.y - Y_RECYCLE_CUTOFF;
lower_extremity_cutoff = player.localPosition.y + Y_RECYCLE_CUTOFF;
float temp_pos, temp_scale;
//find the smallest active right extremity
float prev_extremity = float.MinValue;
int stage = 1;
for (int a = 0; a < all_platforms.Count; ++a){
//when the first right extremity within the active x range is found
if (stage == 1 && right_extremities.ElementAt(a).Key > right_extremity_cutoff){
stage = 2;
right_extremities.ElementAt(a);
//mark the position of the next right extremity that would appear when pushing the borders left
next_left_pos = prev_extremity;
//mark the extremity index
//right_extremity_index = right_extremities.ElementAt(a).Value;
right_extremity_index = a;
//SHOULD THIS SAY DISAPPEAR?
//mark the position of the next right extremity that would appear when pulling the borders to the right
next_left_pos_rep = right_extremities.ElementAt(a).Key;
}
//continue checking platforms until the first which is also within the active y range is found
else if (stage == 2){
temp_pos = all_platforms[right_extremities.ElementAt(a).Value].get_position().y;
temp_scale = all_platforms[right_extremities.ElementAt(a).Value].getScale().y;
//if the platform is within the allowable y range
if (((temp_pos + (temp_scale/2)) > upper_extremity_cutoff) && ((temp_pos - (temp_scale/2)) < lower_extremity_cutoff)){
//mark the extremity position and index
min_x_pos = right_extremities.ElementAt(a).Key;
min_x_index = right_extremities.ElementAt(a).Value;
break;
}
}
prev_extremity = right_extremities.ElementAt(a).Key;
}
//find the largest active left extremity
prev_extremity = float.MaxValue;
stage = 1;
示例11: format
//return formatted input code for the appropriate language
public string format(string input, string language)
{
//read language-specific tokens/keywords and HTML tags from the file we want
StreamReader langfile = new StreamReader("C:\\Users\\Zimmy\\Documents\\Snippit\\Languages\\" + language + ".txt");
//sorted lists containing each keyword or token to format and their corresponding HTML tags
SortedList<string, string> openers = new SortedList<string, string>();
SortedList<string, string> closers = new SortedList<string, string>();
string[] cols = new string[3]; //holds each value for each row of data
char[] delimiters = {'\t'}; //each value is separated by tab
string line; //a line of text that is read in
//read in each line, placing the keyword/token and
//it's opening or closing HTML tag into the appropriate SortedList
while((line = langfile.ReadLine()) != null)
{
cols = line.Split(delimiters);
openers.Add(cols[0], cols[1]);
closers.Add(cols[0], cols[2]);
}
//close the StreamReader
langfile.Close();
//read language-specific tokens/keywords and HTML tags from the file we want
StreamReader delfile = new StreamReader("C:\\Users\\Zimmy\\Documents\\Snippit\\Languages\\" + language + "dels.txt");
string del; //delimiter that is read in
string dels = @""; //list of delimiters that breaks the code into tokens
//get each delimiter from the delimiter file and add it to the list
del = delfile.ReadLine();
dels += "(" + del.ToString() + ")";
while ((del = delfile.ReadLine()) != null)
{
dels += "|(" + del.ToString() + ")";
}
//close the StreamReader
delfile.Close();
string separators = @"(\"")|( )|(&)|(%)|($)|(#)|(!)|(\-)|(//)|(/\*)|(\')|(\*\/)|(\()|(\))|(\*)|(,)|(\.)|(:)|(;)|(\?)|(@)|(\[)|(\])|(^)|(`)|(\{)|(\|)|(\})|(~)|(\+)|(<)|(=)|(\n)|(\t)|(>)";
//string[] tokens = System.Text.RegularExpressions.Regex.Split(input, separators);
string[] tokens = System.Text.RegularExpressions.Regex.Split(input, dels);
string fcode = "";
foreach (string token in tokens)
{
if (openers.ContainsKey(token))
{
fcode += openers.ElementAt(openers.IndexOfKey(token)).Value + token
+ closers.ElementAt(closers.IndexOfKey(token)).Value;
}
else
{
fcode += token;
}
}
return fcode;
}
示例12: DrawToBuffer
//Здесь будет происходить отрисовка кадра в буфер
public void DrawToBuffer()
{
int drawNum = 0;
//List<DrawableObject> list = new List<DrawableObject>();
SortedList<int, DrawableObject> list= new SortedList<int, DrawableObject>();
if (System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.Z) == true)
//if (System.Windows.Input.Keyboard.GetKeyStates(System.Windows.Input.Key.Space)>0) //Отлично, для этого он просит запилить потоки и прочую чешую. Разобраться
grafx.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(255, 128, 0, 0)), 0, 0, view.width, view.height);
else
grafx.Graphics.FillRectangle(Brushes.Black, 0, 0,view.width, view.height);
foreach(Layer layer in game.objectManager.Layers)
{
DrawableObject obj = layer.getNextObject();
while (obj != null)
{
if ((obj.position.X + obj.width > view.x) && (obj.position.X < view.x + view.width) && (obj.position.Y + obj.height * 2 > view.y) && (obj.position.Y < view.y + view.height))
{
//list.Add(obj.depth, obj);
obj.Draw(grafx, (float)(obj.position.X - view.x), (float)(obj.position.Y - view.y));
drawNum++;
}
obj = layer.getNextObject();
}
};
/*list.Sort(delegate(DrawableObject x, DrawableObject y)
{
if (x.depth == y.depth) return 0;
else if (x.depth > y.depth) return -1;
else return 1;
});*/
for (int i = 0; i < list.Count; i++)
{
DrawableObject obj = list.ElementAt(i).Value;
obj.Draw(grafx, (float)(obj.position.X - view.x), (float)(obj.position.Y - view.y));
}
// foreach (DrawableObject obj in list)
// {
// obj.Draw(grafx, (float)(obj.position.X - view.x), (float)(obj.position.Y - view.y));
// }
grafx.Graphics.DrawString(Convert.ToString(fps), font, Brushes.Red, new Point(0, 0));
grafx.Graphics.DrawString(Convert.ToString(drawNum), font, Brushes.Red, new Point(0, 30));
grafx.Graphics.DrawLine(new Pen(Color.White,64.0f), new Point((int)-view.x, game.gameLogic.stageHeight - (int)view.y), new Point(game.gameLogic.stageWidth - (int)view.x, game.gameLogic.stageHeight - (int)view.y));
}
示例13: StartRanking
/// <summary>
/// evaluates the relevant documents according to a specific query
/// </summary>
/// <param name="queryDocs">list of relevant documents to be evaluated with the required data for the evaluating process</param>
/// <param name="dDocs">documents metada</param>
/// <returns>list of QueryDocs, sorted from the most relevant to the least</returns>
internal List<string> StartRanking(Dictionary<string, QueryDoc> queryDocs, Dictionary<string, Doc> dDocs)
{
List<string> ans = new List<string>();
SortedList<double, List<string>> docsRanks = new SortedList<double, List<string>>();
//calculates number of terms in query
int termsInQuery = Parse.d_abNumTerms.Count + Parse.d_cfTerms.Count + Parse.d_gmTerms.Count + Parse.d_nrTerms.Count + Parse.d_szTerms.Count;
int maxTf;
double wij, idf, tfij, wiq;
double sigmaWijWiq = 0;
//double sigmaWijSqr = 0;
double sigmaWiqSqr = 0;
int numOfDocsInEngine = dDocs.Count;
foreach (QueryDoc qd in queryDocs.Values)
{
maxTf = dDocs[qd.docName].maxtfCount;
foreach (QueryTerm qt in qd.queryTerm)
{
//reuse idf values to avoid recalculation
if (!(termsData.ContainsKey(qt.term.termString)))
{
idf = Math.Log((numOfDocsInEngine / qt.term.d_docTf.Count), 2);
termsData[qt.term.termString] = idf;
}
else
idf = termsData[qt.term.termString];
wiq = 1;
//term frequency in doc normalized by maxTf in doc
tfij = (double)(qt.term.d_docTf[qd.docName]) / (double)maxTf;
//mult tfij by 1.2 if term appears in doc's header
if (qt.term.d_docHeader[qd.docName] == true)
tfij *= 1.2;
wij = idf * tfij;
//add more weight if term exists in header
if (qt.term.d_docHeader.ContainsKey(qd.docName))
sigmaWijWiq += ((double)wiq * wij) * 1.1;
else
sigmaWijWiq += (double)wiq * wij;
//sigmaWijWiq += (double)wiq * wij;
//sigmaWijSqr += Math.Pow(wij, 2);
sigmaWijWiq += (double)wiq * wij;
sigmaWiqSqr += Math.Pow(wiq, 2);
}
//calculate cosine
double docsSigmaWijSqr = dDocs[qd.docName].sigmaWijSqr;
double cosineDenominator = docsSigmaWijSqr * sigmaWiqSqr;
cosineDenominator = Math.Sqrt(cosineDenominator);
if (termsInQuery == qd.queryTerm.Count)
sigmaWijWiq *= 1.2;
double cosine = sigmaWijWiq / cosineDenominator;
//insert result to docsRanks
if (docsRanks.ContainsKey(cosine))
{
docsRanks[cosine].Add(qd.docName);
}
else
{
List<string> toAdd = new List<string>();
toAdd.Add(qd.docName);
docsRanks.Add(cosine, toAdd);
}
sigmaWijWiq = 0;
sigmaWiqSqr = 0;
}
//now i have docs ranks, need to extract top 50
int resultsCount = 0;
KeyValuePair<double, List<string>> docList;
for (int i = docsRanks.Count - 1; i >= 0; i-- )
{
if (resultsCount == 50)
break;
docList = docsRanks.ElementAt(i);
foreach (string doc in docList.Value)
{
ans.Add(doc);
resultsCount++;
if (resultsCount == 50)
break;
//.........这里部分代码省略.........
示例14: getRequest
string getRequest(string text)
{
System.Collections.Generic.SortedList<string, string> paramsOrdered = new SortedList<string, string>();
paramsOrdered.Add("user", user);
paramsOrdered.Add("voice", "Philippe");
paramsOrdered.Add("coding", "lin");
paramsOrdered.Add("parsing", "tags");
paramsOrdered.Add("frequency", "48000");
paramsOrdered.Add("header", "wav-header");
byte[] bytes = Encoding.UTF8.GetBytes(text);
//Console.Write(BitConverter.ToString(bytes));
paramsOrdered.Add("text", Encoding.UTF8.GetString(bytes));
//Calcul de la valeur de hashsage
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(key);
System.Security.Cryptography.HMACMD5 hmacMD5 = new System.Security.Cryptography.HMACMD5(keyByte);
hmacMD5.Initialize();
string concatParams = "";
for (int i = 0; i < paramsOrdered.Count; i++)
concatParams += paramsOrdered.ElementAt(i).Key + "=" + paramsOrdered.ElementAt(i).Value;
byte[] hashByte = hmacMD5.ComputeHash(encoding.GetBytes(concatParams));
// Construction de l'url d'invocation
string webRequestString = @"http://ws.voxygen.fr/ws/tts1?";
for (int i = 0; i < paramsOrdered.Count; i++)
{
if (i > 0) webRequestString += "&";
webRequestString += paramsOrdered.ElementAt(i).Key + "=" + paramsOrdered.ElementAt(i).Value;
}
webRequestString += "&hmac=" + ByteToString(hashByte);
return webRequestString;
}
示例15: Convert_USGS_to_ClimateData
//.........这里部分代码省略.........
//initialize currentYear and month
currentYear = climate_Dic.First().Key.Substring(0, 4).ToString();
//starting timestep
currentTimeS = 0;
currentMonth = Convert.ToInt16(climate_Dic.First().Key.Substring(5, 2).ToString());
tempEco = 1;
lastYear = climate_Dic.AsEnumerable().Select(ax => Convert.ToInt32(ax.Key.Substring(0, 4).ToString())).Distinct().ToList().Max();
firstYear = climate_Dic.AsEnumerable().Select(ai => Convert.ToInt32(ai.Key.Substring(0, 4).ToString())).Distinct().ToList().Min();
if ((double)climate_Dic.Count / 12 > (double)lastYear - firstYear)
lastYear = lastYear - 1;
for (int j = firstYear; j <= lastYear; j++)
{
for (int i = 0; i < climateFileActiveEcoregions.Count; i++)
{
currentYear = j.ToString();
foreach (KeyValuePair<string, double[]> row in climate_Dic)
{
if (currentYear == row.Key.Substring(0, 4).ToString())
{
if (currentMonth == Convert.ToInt16(row.Key.Substring(5, 2)))
{
AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
sumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
numberOfDays++;
}
else
{
if (exportToTxtFormatFile)
file.WriteLine(climateFileActiveEcoregions.ElementAt(i).Value.Name + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(SumPrecp, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\t" + "0.0" + "\t" + Math.Round(AverageSTDT / numberOfDays, 2) + "\t" + Math.Round(sumVarPpt, 2) + "\n");
//file.WriteLine("eco1" + "\t" + currentYear + "\t" + currentMonth + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(AverageMaxSTD / numberOfDays, 2) + "\t" + Math.Round(AverageMinT / numberOfDays, 2) + "\t" + Math.Round(AverageMinSTD / numberOfDays, 2) + "\t" + Math.Round(AveragePrec / numberOfDays, 2) + "\t" + Math.Round(AveragePrecSTD / numberOfDays, 2) + "\n");
//tempMonth = currentMonth;
currentMonth = Convert.ToInt16(row.Key.Substring(5, 2));
//if (tempMonth != currentMonth)
AverageMax = 0;
//AverageMaxSTD = 0;
AverageMin = 0;
//AverageMinSTD = 0;
SumPrecp = 0;
//AveragePrecSTD = 0;
AverageSTDT = 0;
sumVarPpt = 0;
numberOfDays = 0;
AverageMin += Math.Round(row.Value[IndexMinT_Mean], 2);
AverageMax += Math.Round(row.Value[IndexMaxT_Mean], 2);
SumPrecp += (Math.Round(row.Value[IndexPrcp_Mean], 2));
AverageSTDT += Math.Round((row.Value[IndexMaxT_Var] + row.Value[IndexMinT_Var]) / 2, 2);
sumVarPpt += Convert.ToDouble(row.Value[IndexPrcp_STD]);
//sums = 0;
//stdTemp = 0;
//prpSums = 0;
//stdPrp = 0;
numberOfDays++;
}
}
else // currentYear != row.Key.Substring(0, 4).ToString())
{
//if (tempEco != i && currentMonth == 12)
// file.WriteLine("eco" + tempEco.ToString() + "\t" + currentTimeS + "\t" + currentMonth + "\t" + Math.Round(AverageMin / numberOfDays, 2) + "\t" + Math.Round(AverageMax / numberOfDays, 2) + "\t" + Math.Round(Math.Sqrt(AverageSTDT / numberOfDays), 2) + "\t" + Math.Round(AveragePrecp / numberOfDays, 2) + "\t" + Math.Round(StdDevPpt, 2) + "\t" + "0.0" + "\n");
if (exportToTxtFormatFile)