public Main(string trainFile, string testFile, int k){ // train BufferedReader trainingDataSet = readDataFile(trainFile); trainingCadidateList = loadCandidateList(trainingDataSet); // test BufferedReader testDataSet = readDataFile(testFile); testCadidateList = loadCandidateList(testDataSet); finalTestCadidateList = new ArrayList<Candidate>(); kNearestNighbour(trainingCadidateList, testCadidateList, k); double count = 0; double matched = 0; for(Candidate testC : testCadidateList){ string stringC = testC.toString(); string finalCan = finalTestCadidateList.get((int)count).ToString(); if(testC.getIntClass() == finalTestCadidateList.get((int)count).getIntClass()){ matched++; Console.WriteLine(stringC+" "+finalCan+ " MATCHED"); }else{ Console.WriteLine(stringC+" "+finalCan+ " UNMATCHED"); } count++; } Console.Write(matched+"/"+count); Console.Write(" %.2f",matched/count*100); Console.Write("%"); }
public void testGenerateCorrectWhenGapMovedRightward() { board.moveGapLeft();// gives { 1, 2, 5, 3, 0, 4, 6, 7, 8 } Assert.assertEquals(new EightPuzzleBoard(new int[] { 1, 2, 5, 3, 0, 4, 6, 7, 8 }), board); List<Action> actions = new ArrayList<Action>(EightPuzzleFunctionFactory .getActionsFunction().actions(board)); Assert.assertEquals(4, actions.size()); EightPuzzleBoard expectedFourth = new EightPuzzleBoard(new int[] { 1, 2, 5, 3, 4, 0, 6, 7, 8 }); EightPuzzleBoard actualFourth = (EightPuzzleBoard) (EightPuzzleBoard) EightPuzzleFunctionFactory .getResultFunction().result(board, actions.get(3)); Assert.assertEquals(expectedFourth, actualFourth); Assert.assertEquals(EightPuzzleBoard.RIGHT, actions.get(3)); }
public void testComplexBoardSuccessorGenerator() { List<Action> actions = new ArrayList<Action>(af.actions(eightBoard)); Assert.assertEquals(8, actions.size()); NQueensBoard next = (NQueensBoard) rf .result(eightBoard, actions.get(0)); Assert.assertEquals(1, next.getNumberOfQueensOnBoard()); actions = new ArrayList<Action>(af.actions(next)); Assert.assertEquals(6, actions.size()); }
public void testGenerateCorrect3Successors() { List<Action> actions = new ArrayList<Action>(EightPuzzleFunctionFactory .getActionsFunction().actions(board)); Assert.assertEquals(3, actions.size()); // test first successor EightPuzzleBoard expectedFirst = new EightPuzzleBoard(new int[] { 1, 2, 0, 3, 4, 5, 6, 7, 8 }); EightPuzzleBoard actualFirst = (EightPuzzleBoard) EightPuzzleFunctionFactory .getResultFunction().result(board, actions.get(0)); Assert.assertEquals(expectedFirst, actualFirst); Assert.assertEquals(EightPuzzleBoard.UP, actions.get(0)); // test second successor EightPuzzleBoard expectedSecond = new EightPuzzleBoard(new int[] { 1, 2, 5, 3, 4, 8, 6, 7, 0 }); EightPuzzleBoard actualSecond = (EightPuzzleBoard) EightPuzzleFunctionFactory .getResultFunction().result(board, actions.get(1)); Assert.assertEquals(expectedSecond, actualSecond); Assert.assertEquals(EightPuzzleBoard.DOWN, actions.get(1)); // test third successor EightPuzzleBoard expectedThird = new EightPuzzleBoard(new int[] { 1, 2, 5, 3, 0, 4, 6, 7, 8 }); EightPuzzleBoard actualThird = (EightPuzzleBoard) (EightPuzzleBoard) EightPuzzleFunctionFactory .getResultFunction().result(board, actions.get(2)); Assert.assertEquals(expectedThird, actualThird); Assert.assertEquals(EightPuzzleBoard.LEFT, actions.get(2)); }
/// <summary> /// 接受请求 /// </summary> /// <param name="param">参数</param> private static void readData(object param) { Socket socket = (Socket)param; FCHttpMonitor nodeService = FCHttpMonitor.MainMonitor; int newSocketID = (int)socket.Handle; try { byte[] buffer = new byte[102400]; int len = socket.Receive(buffer); MemoryStream memoryStream = new MemoryStream(buffer); StreamReader reader = new StreamReader(memoryStream); FCHttpData data = new FCHttpData(); data.m_remoteIP = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); data.m_remotePort = ((IPEndPoint)socket.RemoteEndPoint).Port; String requestHeader; int contentLength = 0; string parameters = ""; while ((requestHeader = reader.ReadLine()) != null && !String.IsNullOrEmpty(requestHeader)) { String lowerHeader = requestHeader.ToLower(); if (lowerHeader.IndexOf("get") == 0) { int end = lowerHeader.IndexOf("http/"); data.m_method = "GET"; parameters = requestHeader.Substring(5, end - 6); } else if (lowerHeader.IndexOf("post") == 0) { int end = lowerHeader.IndexOf("http/"); data.m_method = "POST"; parameters = requestHeader.Substring(5, end - 6); } else if (lowerHeader.IndexOf("accept: ") == 0) { try { data.m_contentType = requestHeader.Substring(8, requestHeader.IndexOf(',') - 8); } catch { } } else if (lowerHeader.IndexOf("content-type:") == 0) { data.m_contentType = requestHeader.Substring(14); } else if (lowerHeader.IndexOf("host:") == 0) { data.m_url = requestHeader.Substring(requestHeader.IndexOf(':') + 2); } else if (lowerHeader.IndexOf("content-length") == 0) { int begin = lowerHeader.IndexOf("content-length:") + "content-length:".Length; String postParamterLength = requestHeader.Substring(begin).Trim(); contentLength = Convert.ToInt32(postParamterLength); } } if (contentLength > 0) { int idx = 0, ide = 0; data.m_body = new byte[contentLength]; while (idx < contentLength) { int recvData = reader.Read(); if (recvData != -1) { if (recvData != 0) { ide++; } idx++; } else { break; } } reader.Close(); memoryStream.Dispose(); if (ide == 0) { socket.Receive(data.m_body); } else { for (int i = 0; i < contentLength; i++) { data.m_body[i] = buffer[len - contentLength + i]; } } data.m_contentLength = contentLength; } else { reader.Close(); memoryStream.Dispose(); } if (data.m_method.Length == 0) { return; } int cindex = parameters.IndexOf('?'); if (cindex != -1) { data.m_url = data.m_url + "/" + parameters; parameters = parameters.Substring(cindex + 1); String[] strs = parameters.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries); int strsSize = strs.Length; for (int i = 0; i < strsSize; i++) { String[] subStrs = strs[i].Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); data.m_parameters.put(subStrs[0].ToLower(), subStrs[1]); } } else { data.m_url += "/" + parameters; } FCScript indicator = null; if (nodeService.UseScript) { try { lock (nodeService.m_indicators) { indicator = nodeService.m_indicators.Pop(); } } catch { indicator = CFunctionEx.CreateScript(nodeService.Script, nodeService.Native); } ArrayList <CFunction> functions = indicator.getFunctions(); int functionsSize = functions.Count; for (int i = 0; i < functionsSize; i++) { CFunctionHttp function = functions.get(i) as CFunctionHttp; if (function != null) { function.m_data = data; } } } data.m_socketID = newSocketID; lock (nodeService.m_httpDatas) { nodeService.m_httpDatas.put(newSocketID, data); } if (indicator != null) { indicator.callFunction("ONHTTPREQUEST();"); } if (data.m_close) { return; } int resContentLength = 0; if (data.m_resBytes != null) { resContentLength = data.m_resBytes.Length; } else { if (data.m_resStr != null) { resContentLength = Encoding.Default.GetBytes(data.m_resStr).Length; } } StringBuilder bld = new StringBuilder(); bld.Append("HTTP/1.0 " + data.m_statusCode.ToString() + " OK\r\n"); bld.Append(String.Format("Content-Length: {0}\r\n", resContentLength)); bld.Append("Connection: close\r\n\r\n"); if (data.m_resBytes != null) { socket.Send(Encoding.Default.GetBytes(bld.ToString())); socket.Send(data.m_resBytes); } else { bld.Append(data.m_resStr); socket.Send(Encoding.Default.GetBytes(bld.ToString())); } if (indicator != null) { lock (nodeService.m_indicators) { nodeService.m_indicators.Push(indicator); } } } catch (Exception ex) { Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace); } finally { lock (nodeService.m_httpDatas) { nodeService.m_httpDatas.Remove(newSocketID); } socket.Close(); } }
/// <summary> /// 重置布局 /// </summary> public virtual bool OnResetLayout() { if (Native != null) { if (m_columnsCount > 0 && m_rowsCount > 0 && m_columnStyles.size() > 0 && m_rowStyles.size() > 0) { int width = Width, height = Height; int tabControlsSize = m_tableControls.size(); //获取行列的宽度 int[] columnWidths = new int[m_columnsCount]; int[] rowHeights = new int[m_rowsCount]; //获取列的宽度 int allWidth = 0, allHeight = 0; for (int i = 0; i < m_columnsCount; i++) { FCColumnStyle columnStyle = m_columnStyles.get(i); int cWidth = 0; FCSizeType sizeType = columnStyle.SizeType; float sWidth = columnStyle.Width; if (sizeType == FCSizeType.AbsoluteSize) { cWidth = (int)(sWidth); } else if (sizeType == FCSizeType.AutoFill) { cWidth = width - allWidth; } else if (sizeType == FCSizeType.PercentSize) { cWidth = (int)(width * sWidth); } columnWidths[i] = cWidth; allWidth += cWidth; } for (int i = 0; i < m_rowsCount; i++) { FCRowStyle rowStyle = m_rowStyles.get(i); //获取行的高度 int rHeight = 0; FCSizeType sizeType = rowStyle.SizeType; float sHeight = rowStyle.Height; if (sizeType == FCSizeType.AbsoluteSize) { rHeight = (int)(sHeight); } else if (sizeType == FCSizeType.AutoFill) { rHeight = height - allHeight; } else if (sizeType == FCSizeType.PercentSize) { rHeight = (int)(height * sHeight); } rowHeights[i] = rHeight; allHeight += rHeight; } //控制控件的大小和位置 for (int i = 0; i < tabControlsSize; i++) { FCView control = m_tableControls.get(i); int column = m_columns[i]; int row = m_rows[i]; FCPadding margin = control.Margin; //获取横坐标和纵坐标 int cLeft = 0, cTop = 0; for (int j = 0; j < column; j++) { cLeft += columnWidths[j]; } for (int j = 0; j < row; j++) { cTop += rowHeights[j]; } int cRight = cLeft + columnWidths[column] - margin.right; int cBottom = cTop + rowHeights[row] - margin.bottom; cLeft += margin.left; cTop += margin.top; if (cRight < cLeft) { cRight = cLeft; } if (cBottom < cTop) { cBottom = cTop; } control.Bounds = new FCRect(cLeft, cTop, cRight, cBottom); } } } return(true); }
public void run() { // output needs to be the size of the data, remove excess 00 00? //byte[] buffer = new byte[2000]; // create a large buffer, should be able to hold all traffic ArrayList <Byte> aBuffer = new ArrayList <Byte>(); ArrayList <Byte> aOutput = new ArrayList <Byte>(); // create a large buffer, should be able to hold all traffic // byte decompressBuffer[] = new byte[2000]; while (run) { System.Threading.Thread.Sleep(5); if (!client.isConnected()) { writeoutput("Disconnected"); packetOperator.processDisconnect(); } try { int size = myin.available(); if (size != 0) { byte[] incoming = new byte[myin.available()]; myin.read(incoming); for (int i = 0; i < incoming.length; i++) { aBuffer.add(incoming[i]); } // fills our vecotor with the packet } while (!aBuffer.isEmpty()) { if (bDecompress) { byte[] tempbuf = new byte[aBuffer.size()]; // create a buffer to hold list for (int x = 0; x < aBuffer.size(); x++) { tempbuf[x] = aBuffer.get(x); } // adds list to buffer if (aBuffer.size() > 1000) { int zx = 55 + 5; } huffmanobject myhuf = new huffmanobject(); myhuf.buffer = tempbuf; myhuf.src_size = tempbuf.length; myhuf.out_size = 0; myhuf = BinaryNode.drkDecompress(myhuf); byte[] temp = myhuf.output; if (temp.length < 1) { aBuffer.clear(); break; } // if we are getting garbage wipe the buffer. if (tempbuf.length > temp.length) { writeoutput("Packet: " + aBuffer.size() + "bytes consumed: " + myhuf.out_size); int intx = 1; for (int x = 0; x < temp.length; x++) { aOutput.add(temp[x]); } // outputs the packet for (int x = 0; x < myhuf.out_size + intx; x++) { aBuffer.remove(0); } // removes it from queue } else { for (int x = 0; x < temp.length; x++) { aOutput.add(temp[x]); } // outputs the packet if (aBuffer.isEmpty() == false) { aBuffer.clear(); } } } else { byte[] temp = new byte[aBuffer.size()]; // create a buffer to hold list for (int x = 0; x < aBuffer.size(); x++) { temp[x] = aBuffer.get(x); } // adds list to buffer if (aBuffer.isEmpty() == false) { aBuffer.clear(); } for (int x = 0; x < temp.length; x++) { aOutput.add(temp[x]); } } byte[] temp = new byte[aOutput.size()]; for (int x = 0; x < aOutput.size(); x++) { temp[x] = aOutput.get(x); } handlePacket(temp); aOutput.clear(); } } // end of newdata IF // end of try catch (SocketException e) { writeoutput("Socket Error: Most likely disconnect: " + e); try { client.close(); } catch (IOException e2) {} packetOperator.processDisconnect(); } catch (IOException e) { writeoutput("IOError: " + e); } catch (NegativeArraySizeException e) { } catch (Exception e) { writeoutput("Some other error in the thread: " + e); e.printStackTrace(); } } }
public string GetWord(int index) { return((string)tokens.get(index)); }
/* **************************************************************************** * addXRIDescriptors() **************************************************************************** */ /** * Adds the specified XRI Descriptors to the chain */ public void addXRIDescriptors(ArrayList oDescriptors) { for (int i = 0; i < oDescriptors.Count; i++) { addXRIDescriptor((XRD)oDescriptors.get(i)); } }
public Value execute(Env env) { try { return(_block.execute(env)); } catch (QuercusLanguageException e) { Value value = null; try { value = e.toValue(env); } catch (Throwable e1) { throw new QuercusRuntimeException(e1); } for (int i = 0; i < _catchList.size(); i++) { Catch item = _catchList.get(i); if (value != null && value.isA(env, item.getId()) || item.getId().equalsString("Exception")) { if (value != null) { item.getExpr().evalAssignValue(env, value); } else { item.getExpr().evalAssignValue(env, NullValue.NULL); } return(item.getBlock().execute(env)); } } throw e; } catch (QuercusDieException e) { for (int i = 0; i < _catchList.size(); i++) { Catch item = _catchList.get(i); if (item.getId().equalsString("QuercusDieException")) { item.getExpr().evalAssignValue(env, env.createException(e)); return(item.getBlock().execute(env)); } } throw e; } catch (QuercusExitException e) { for (int i = 0; i < _catchList.size(); i++) { Catch item = _catchList.get(i); if (item.getId().equalsString("QuercusExitException")) { item.getExpr().evalAssignValue(env, env.createException(e)); return(item.getBlock().execute(env)); } } throw e; } catch (Exception e) { for (int i = 0; i < _catchList.size(); i++) { Catch item = _catchList.get(i); if (item.getId().equalsString("Exception")) { Throwable cause = e; //if (e instanceof QuercusException && e.getCause() != null) //cause = e.getCause(); item.getExpr().evalAssignValue(env, env.createException(cause)); return(item.getBlock().execute(env)); } } if (e instanceof QuercusException) { throw (QuercusException)e; }
// // OuterIterator // public override RecursiveIterator getInnerIterator() { int i = _iterStack.size() - 1; return(_iterStack.get(i)); }
public String[] split(String regex, int limit) { /* fastpath if the regex is a * (1)one-char String and this character is not one of the * RegEx's meta characters ".$|()[{^?*+\\", or * (2)two-char String and the first char is the backslash and * the second is not the ascii digit or ascii letter. */ char ch = (char)0; if (((regex.value.Length == 1 && new String(".$|()[{^?*+\\").indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\\' && (((ch = regex.charAt(1)) - '0') | ('9' - ch)) < 0 && ((ch - 'a') | ('z' - ch)) < 0 && ((ch - 'A') | ('Z' - ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList <String> list = new ArrayList <String>(); while ((next = indexOf(ch, off)) != -1) { if (!limited || list.size() < limit - 1) { list.add(substring(off, next)); off = next + 1; } else // last one //assert (list.size() == limit - 1); { list.add(substring(off, value.Length)); off = value.Length; break; } } // If no match was found, return this if (off == 0) { return new String[] { this } } ; // Add remaining segment if (!limited || list.size() < limit) { list.add(substring(off, value.Length)); } // Construct result int resultSize = list.size(); if (limit == 0) { while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { resultSize--; } } String[] result = new String[resultSize]; return(list.subList(0, resultSize).toArray(result)); } return(Pattern.compile(regex).split(this, limit)); }
public static int search(ArrayList src, ArrayList pattern, int start) { int result = -1; int num = 0; if (start > src.size() - pattern.size()) { return(-1); } int num2; for (;;) { num2 = src.subList(num + start, src.size() - pattern.size() + 1).indexOf(pattern.get(0)); if (num2 == -1) { break; } int num3 = 1; for (int i = 1; i < pattern.size(); i++) { if (!String.instancehelper_equals((string)src.get(num + start + num2 + i), pattern.get(i))) { result = -1; num3 = 0; break; } } if (num3 != 0) { goto Block_5; } num += num2 + 1; if (num + start >= src.size()) { return(result); } } return(num2); Block_5: result = num + num2; return(result); }
/// <summary> /// 触摸移动方法 /// </summary> /// <param name="touchInfo">触摸信息</param> public override void onTouchMove(FCTouchInfo touchInfo) { callTouchEvents(FCEventID.TOUCHMOVE, touchInfo); FCGrid grid = Grid; if (m_band != null && grid != null) { FCPoint mp = touchInfo.m_firstPoint; if (AllowResize) { ArrayList <FCBandedFCGridColumn> bandColumns = m_band.getColumns(); int columnsSize = bandColumns.size(); int index = -1; int width = Width; for (int i = 0; i < columnsSize; i++) { if (this == bandColumns.get(i)) { index = i; break; } } if (m_resizeState > 0) { FCPoint curPoint = Native.TouchPoint; int newWidth = m_beginWidth + (curPoint.x - m_touchDownPoint.x); if (newWidth > 0) { if (m_resizeState == 1) { FCBandedFCGridColumn leftColumn = bandColumns.get(index - 1); int leftWidth = leftColumn.Width; leftColumn.Width = newWidth; width += leftWidth - newWidth; Width = width; } else if (m_resizeState == 2) { Width = newWidth; FCBandedFCGridColumn rightColumn = bandColumns.get(index + 1); int rightWidth = rightColumn.Width; rightWidth += width - newWidth; rightColumn.Width = rightWidth; } } grid.invalidate(); return; } else { FCCursors oldCursor = Cursor; FCCursors newCursor = oldCursor; if ((index > 0 && mp.x < 5) || (index < columnsSize - 1 && mp.x > width - 5)) { newCursor = FCCursors.SizeWE; } else { newCursor = FCCursors.Arrow; } if (oldCursor != newCursor) { Cursor = newCursor; invalidate(); } } if (!IsDragging) { Cursor = FCCursors.Arrow; } } } }
public void write(int i, int j, byte[] abyte0, int k) { try { int l = getOffset(i, j); int i1 = l >> 8; int l1 = l & 0xff; int i2 = (k + 5) / 4096 + 1; if (i2 >= 256) { return; } if (i1 != 0 && l1 == i2) { debug("SAVE", i, j, k, "rewrite"); write(i1, abyte0, k); } else { for (int j2 = 0; j2 < l1; j2++) { sectorFree.set(i1 + j2, Boolean.valueOf(true)); } int k2 = sectorFree.indexOf(Boolean.valueOf(true)); int l2 = 0; if (k2 != -1) { int i3 = k2; do { if (i3 >= sectorFree.size()) { break; } if (l2 != 0) { if (((Boolean)sectorFree.get(i3)).booleanValue()) { l2++; } else { l2 = 0; } } else if (((Boolean)sectorFree.get(i3)).booleanValue()) { k2 = i3; l2 = 1; } if (l2 >= i2) { break; } i3++; } while (true); } if (l2 >= i2) { debug("SAVE", i, j, k, "reuse"); int j1 = k2; setOffset(i, j, j1 << 8 | i2); for (int j3 = 0; j3 < i2; j3++) { sectorFree.set(j1 + j3, Boolean.valueOf(false)); } write(j1, abyte0, k); } else { debug("SAVE", i, j, k, "grow"); dataFile.seek(dataFile.length()); int k1 = sectorFree.size(); for (int k3 = 0; k3 < i2; k3++) { dataFile.write(emptySector); sectorFree.add(Boolean.valueOf(false)); } sizeDelta += 4096 * i2; write(k1, abyte0, k); setOffset(i, j, k1 << 8 | i2); } } setChunkTimestamp(i, j, (int)(java.lang.System.currentTimeMillis() / 1000L)); } catch (IOException ioexception) { ioexception.printStackTrace(); } }
/// <summary> /// 添加节点 /// </summary> /// <param name="index">行索引</param> public virtual void onAddingNode(int index) { FCGridRow row = Row; if (Row == null) { //创建行 row = new FCGridRow(); FCTreeNode parentNode = m_parent; if (parentNode == null) { if (index != -1) { //插入行 m_tree.insertRow(index, row); //重置行的索引 ArrayList <FCGridRow> rows = m_tree.getRows(); int rowSize = rows.size(); for (int i = 0; i < rowSize; i++) { rows.get(i).Index = i; } } else { //添加行 m_tree.addRow(row); //设置索引 ArrayList <FCGridRow> rows = m_tree.getRows(); row.Index = rows.size() - 1; } row.addCell(0, this); m_targetColumn = m_tree.getColumn(0); } else { //获取行索引 int rowIndex = parentNode.Row.Index + 1; if (index != -1) { rowIndex = index; } else { //查找上个节点 FCTreeNode lastNode = getLastNode(parentNode.getChildNodes()); if (lastNode != null) { if (lastNode.Row == null) { return; } rowIndex = lastNode.Row.Index + 1; } } //插入行 m_tree.insertRow(rowIndex, row); ArrayList <FCGridRow> rows = m_tree.getRows(); int rowSize = rows.size(); //重置索引 if (rowIndex == rowSize - 1) { row.Index = rowIndex; } else { for (int i = 0; i < rowSize; i++) { rows.get(i).Index = i; } } row.addCell(0, this); m_targetColumn = m_tree.getColumn(parentNode.m_targetColumn.Index + 1); } ColSpan = m_tree.getColumns().size(); //添加子节点 if (m_nodes != null && m_nodes.size() > 0) { int nodeSize = m_nodes.size(); for (int i = 0; i < nodeSize; i++) { m_nodes.get(i).onAddingNode(-1); } } row.Visible = isNodeVisible(this); } }
/// <summary> /// 重置日期图层 /// </summary> /// <param name="state">状态</param> public virtual void onResetDiv(int state) { if (m_calendar != null) { int thisStartYear = m_startYear; int lastStartYear = m_startYear - 12; int nextStartYear = m_startYear + 12; int left = 0; int headHeight = m_calendar.HeadDiv.Height; int top = headHeight; int width = m_calendar.Width; int height = m_calendar.Height; height -= m_calendar.TimeDiv.Height; int yearButtonHeight = height - top; if (yearButtonHeight < 1) { yearButtonHeight = 1; } int toY = 0; ArrayList <YearButton> yearButtons = new ArrayList <YearButton>(); if (m_am_Direction == 1) { toY = yearButtonHeight * m_am_Tick / m_am_TotalTick; if (state == 1) { thisStartYear = nextStartYear; lastStartYear = thisStartYear - 12; nextStartYear = thisStartYear + 12; } } else if (m_am_Direction == 2) { toY = -yearButtonHeight * m_am_Tick / m_am_TotalTick; if (state == 1) { thisStartYear = lastStartYear; lastStartYear = thisStartYear - 12; nextStartYear = thisStartYear + 12; } } if (state == 0) { yearButtons = m_yearButtons; } else if (state == 1) { yearButtons = m_yearButtons_am; } int dheight = yearButtonHeight / 3; int buttonSize = yearButtons.size(); for (int i = 0; i < buttonSize; i++) { if (i == 8) { dheight = height - top; } YearButton yearButton = yearButtons.get(i); yearButton.Year = thisStartYear + i; int vOffSet = 0; if (state == 1) { if (m_am_Tick > 0) { yearButton.Visible = true; if (m_am_Direction == 1) { vOffSet = toY - yearButtonHeight; } else if (m_am_Direction == 2) { vOffSet = toY + yearButtonHeight; } } else { yearButton.Visible = false; continue; } } else { vOffSet = toY; } if ((i + 1) % 4 == 0) { FCPoint dp = new FCPoint(left, top + vOffSet); FCSize ds = new FCSize(width - left, dheight); yearButton.Bounds = new FCRect(dp.x, dp.y, dp.x + ds.cx, dp.y + ds.cy); left = 0; if (i != 0 && i != buttonSize - 1) { top += dheight; } } else { FCPoint dp = new FCPoint(left, top + vOffSet); FCSize ds = new FCSize(width / 4 + ((i + 1) % 4) % 2, dheight); yearButton.Bounds = new FCRect(dp.x, dp.y, dp.x + ds.cx, dp.y + ds.cy); left += ds.cx; } } } }
//Function to cross all informations added to this face and evaluate the best values public void Evaluate() { //Evaluate mouth evaluatedMouth = new Rect(0, 0, 0, 0); //Random randomizer = new Random(); //evaluatedMouth = mouths[randomizer.Next(0, mouths.Count - 1)]; //must work a few on the mouth to choose the best one and proceed to histogram check for try to determinate skin color, eye color, hair color etc.. foreach (Rect mouth in mouths) { if (mouth.y < face.y + face.height / 2) continue; if (evaluatedMouth.width > mouth.width) continue; evaluatedMouth = mouth; } //Evaluate eyes evaluatedEyes = new ArrayList<Rect>(); ArrayList<Rect> rightCandidates = new ArrayList<Rect>(); ArrayList<Rect> leftCandidates = new ArrayList<Rect>(); foreach (Rect eye in eyes) { //Ensure the eyes are in the upper half of the img region if (eye.y + eye.height / 2 > face.y + face.height / 2) continue; if (eye.x + eye.width / 2 < face.x + face.width / 2) rightCandidates.add(eye); else leftCandidates.add(eye); } //get centers for each side weighted by their areas int totalAreas = 0; int totalX = 0; int totalY = 0; if (rightCandidates.size() > 0) { foreach (Rect eye in rightCandidates) { int eyeArea = eye.width * eye.height; totalAreas += eyeArea; totalX += (eye.x + eye.width / 2) * eyeArea; totalY += (eye.y + eye.height / 2) * eyeArea; } Point rightPoint = new Point(totalX / totalAreas, totalY / totalAreas); int rightEyeSide = (int)Math.Sqrt((double)totalAreas / (double)rightCandidates.size()); Rect rightEye = new Rect( rightPoint.x - rightEyeSide / 2, rightPoint.y - rightEyeSide / 2, rightEyeSide, rightEyeSide); //rightEye.Offset(-rightEye.Width / 2, -rightEye.Height / 2); evaluatedEyes.add(rightEye); } if (leftCandidates.size() > 0) { totalAreas = 0; totalX = 0; totalY = 0; foreach (Rect eye in leftCandidates) { int eyeArea = eye.width * eye.height; totalAreas += eyeArea; totalX += (eye.x + eye.width / 2) * eyeArea; totalY += (eye.y + eye.height / 2) * eyeArea; } Point leftPoint = new Point(totalX / totalAreas, totalY / totalAreas); int leftEyeSide = (int)Math.Sqrt((double)totalAreas / (double)leftCandidates.size()); Rect leftEye = new Rect( leftPoint.x - leftEyeSide / 2, leftPoint.y - leftEyeSide / 2, leftEyeSide, leftEyeSide); //leftEye.Offset(-leftEye.Width / 2, -leftEye.Height / 2); evaluatedEyes.add(leftEye); } //Check if it is valid isValid = false; if (evaluatedEyes.size() > 2) throw new Exception("Eyes count must be equal or less than two"); if (evaluatedEyes.size() == 2) { isValid = true; //Get the face line data Point eye1Center = new Point(evaluatedEyes.get(0).x + evaluatedEyes.get(0).width / 2, evaluatedEyes.get(0).y + evaluatedEyes.get(0).height / 2); Point eye2Center = new Point(evaluatedEyes.get(1).x + evaluatedEyes.get(1).width / 2, evaluatedEyes.get(1).y + evaluatedEyes.get(1).height / 2); int xOffset = (eye2Center.x - eye1Center.x) / 2; int yOffset = (eye2Center.y - eye1Center.y) / 2; Point eyeLineCenter = new Point(eye1Center.x + xOffset, eye1Center.y + yOffset); int zeroDivFac = eye1Center.x == eye2Center.x ? 1 : 0; //Generate face line slope and offset double aFact = (double)(eye1Center.y - eye2Center.y) / (double)(eye1Center.x - eye2Center.x + zeroDivFac); aFact = Math.Atan(aFact) + Math.PI / 2; aFact = Math.Tan(aFact); double bFact = eyeLineCenter.y - aFact * eyeLineCenter.x; faceLineSlope = aFact; faceLineOffset = bFact; //If the mouth is invalid, project a new based on the face line if (evaluatedMouth.width == 0) { PointGenerator faceLinePoint = new PointGenerator(aFact, bFact); Point projMouthPos = faceLinePoint.GetFromY(face.y + face.height * 0.8); evaluatedMouth = new Rect( projMouthPos.x - (face.width / 3) / 2, projMouthPos.y - (face.height / 5) / 2, face.width / 3, face.height / 5); //evaluatedMouth.Offset(-evaluatedMouth.Width / 2, -evaluatedMouth.Height / 2); } } if (evaluatedEyes.size() == 1 && evaluatedMouth.width > 0) { isValid = true; //Project the other eye based on the mouth //Get the bottom mouth coords Point mouthBottomCenter = new Point( evaluatedMouth.x + evaluatedMouth.width / 2, evaluatedMouth.y + evaluatedMouth.height); //get the facetop coords Point faceTopCenter = new Point(face.width / 2 + face.x, face.y); //Apply an experimental correct factor to the values int correctFact = mouthBottomCenter.x - faceTopCenter.x; //correctFact = (int)(correctFact * 0.5); mouthBottomCenter.x += correctFact; faceTopCenter.x -= correctFact; //Get the slope of the faceline //In case they are the same value, add a pixel to prevent division by 0 int zeroDivFac = mouthBottomCenter.x == faceTopCenter.x ? 1 : 0; double a = (double)(mouthBottomCenter.y - faceTopCenter.y) / (double)(mouthBottomCenter.x - faceTopCenter.x + zeroDivFac); //Get the offset of the face line double b = mouthBottomCenter.y - a * mouthBottomCenter.x; faceLineSlope = a; faceLineOffset = b; //Get the line function of the face PointGenerator faceLinePoint = new PointGenerator(a, b); //Get the reference of the existing eye and its center point Rect eyeRef = evaluatedEyes.get(0); Point eyeCenter = new Point(eyeRef.x + eyeRef.width / 2, eyeRef.y + eyeRef.height / 2); //Get the slope of the eye line (it must be normal to the face line, so we turn it Pi/2 double aEyeFact = Math.Atan(a) + Math.PI / 2; aEyeFact = Math.Tan(aEyeFact); //Get the eye line offset double bEyeFact = eyeCenter.y - aEyeFact * eyeCenter.x; //Get the line function of the eye PointGenerator eyeLinePoint = new PointGenerator(aEyeFact, bEyeFact); //Get the horizontal difference between the center of the existing eye and the face line int diff = faceLinePoint.GetFromY(eyeCenter.y).x - eyeCenter.x; //Get the project eye coords Point projEyePoint = eyeLinePoint.GetFromX(eyeCenter.x + diff * 2); //Get the project eye rectangle Rect projEyeRect = new Rect( projEyePoint.x - eyeRef.width / 2, projEyePoint.y - eyeRef.height / 2, eyeRef.width, eyeRef.height); //projEyeRect.Offset(-eyeRef.Width / 2, -eyeRef.Height / 2); evaluatedEyes.add(projEyeRect); } //If the face keep invalid, put the face line on the middle of the face square if (!isValid) { faceLineSlope = -face.height / 0.01; faceLineOffset = face.y - faceLineSlope * face.x + face.width / 2; } }
private void initFunctionsList() { Collection c = gui.Engine.AllFunctions; Function[] func = (Function[]) c.toArray(new Function[0]); List funcs = new ArrayList(); bool larger = false; funcs.add(0, func[0]); for (int idx = 1; idx <= func.Length - 1; idx++) { int bound = funcs.size(); larger = true; for (int indx = 0; indx < bound; indx++) { int cmpvalue = func[idx].Name.CompareTo(((Function) funcs.get(indx)).Name); if (cmpvalue < 0) { funcs.add(indx, func[idx]); indx = bound; larger = false; } else if (cmpvalue == 0) { indx = bound; larger = false; } } if (larger) { funcs.add(func[idx]); } } dataModel.setFunctions(funcs); functionsTable.ColumnModel.getColumn(0).setPreferredWidth(50); }
// // PRIVATE METHODS // private void checkSuccessorList(ArrayList successorList, String playerToMove, int sizeOfSuccessors) { for (int i = 0; i < successorList.size(); i++) { GameState h = (GameState) successorList.get(i); ArrayList successors2 = new TicTacToe().getSuccessorStates(h); Assert.assertEquals(sizeOfSuccessors, successors2.size()); Assert.assertEquals(playerToMove, new TicTacToe() .getPlayerToMove(h)); } }
public String[] split(CharSequence input, int limit) { int index = 0; boolean matchLimited = limit > 0; ArrayList<String> matchList = new ArrayList<String>(); Matcher m = matcher(input); // Add segments before each match found while(m.find()) { if (!matchLimited || matchList.size() < limit - 1) { String match = input.subSequence(index, m.start()).toString(); matchList.add(match); index = m.end(); } else if (matchList.size() == limit - 1) { // last one String match = input.subSequence(index, input.length()).toString(); matchList.add(match); index = m.end(); } } // If no match was found, return this if (index == 0) return new String[] {input.toString()}; // Add remaining segment if (!matchLimited || matchList.size() < limit) matchList.add(input.subSequence(index, input.length()).toString()); // Construct result int resultSize = matchList.size(); if (limit == 0) while (resultSize > 0 && matchList.get(resultSize-1).equals("")) resultSize--; String[] result = new String[resultSize]; return matchList.subList(0, resultSize).toArray(result); }
public override void clear() { ArrayList toRemove = new ArrayList(); for (Iterator iter = backend.iterator(); iter.hasNext(); ) { DcmElement el = (DcmElement) iter.next(); if (filter(el.tag())) { toRemove.add(el); } } for (int i = 0, n = toRemove.size(); i < n; ++i) { backend.remove(((DcmElement) toRemove.get(i)).tag()); } }
public virtual List align(URL audioUrl, List sentenceTranscript) { List list = this.sentenceToWords(sentenceTranscript); LongTextAligner longTextAligner = new LongTextAligner(list, 3); TreeMap treeMap = new TreeMap(); LinkedList linkedList = new LinkedList(); ArrayDeque arrayDeque = new ArrayDeque(); ArrayDeque arrayDeque2 = new ArrayDeque(); linkedList.offer(new Range(0, list.size())); arrayDeque.offer(list); TimeFrame _INFINITE = TimeFrame.__INFINITE; arrayDeque2.offer(_INFINITE); long end = TimeFrame.__INFINITE.getEnd(); this.languageModel.setText(sentenceTranscript); for (int i = 0; i < 4; i++) { if (i == 1) { this.context.setLocalProperty("decoder->searchManager", "alignerSearchManager"); } while (!arrayDeque.isEmpty()) { if (!SpeechAligner.assertionsDisabled && arrayDeque.size() != linkedList.size()) { throw new AssertionError(); } if (!SpeechAligner.assertionsDisabled && arrayDeque.size() != arrayDeque2.size()) { throw new AssertionError(); } List list2 = (List)arrayDeque.poll(); TimeFrame timeFrame = (TimeFrame)arrayDeque2.poll(); Range range = (Range)linkedList.poll(); this.logger.info(new StringBuilder().append("Aligning frame ").append(timeFrame).append(" to text ").append(list2).append(" range ").append(range).toString()); this.recognizer.allocate(); if (i >= 1) { this.grammar.setWords(list2); } InputStream inputStream = audioUrl.openStream(); this.context.setSpeechSource(inputStream, timeFrame); ArrayList arrayList = new ArrayList(); Result result; while (null != (result = this.recognizer.recognize())) { this.logger.info(new StringBuilder().append("Utterance result ").append(result.getTimedBestResult(true)).toString()); arrayList.addAll(result.getTimedBestResult(false)); } if (i == 0 && arrayList.size() > 0) { end = ((WordResult)arrayList.get(arrayList.size() - 1)).getTimeFrame().getEnd(); } ArrayList arrayList2 = new ArrayList(); Iterator iterator = arrayList.iterator(); while (iterator.hasNext()) { WordResult wordResult = (WordResult)iterator.next(); arrayList2.add(wordResult.getWord().getSpelling()); } int[] array = longTextAligner.align(arrayList2, range); ArrayList arrayList3 = arrayList; this.logger.info(new StringBuilder().append("Decoding result is ").append(arrayList3).toString()); this.dumpAlignmentStats(list, array, arrayList3); for (int j = 0; j < array.Length; j++) { if (array[j] != -1) { treeMap.put(Integer.valueOf(array[j]), arrayList.get(j)); } } inputStream.close(); this.recognizer.deallocate(); } this.scheduleNextAlignment(list, treeMap, linkedList, arrayDeque, arrayDeque2, end); } return(new ArrayList(treeMap.values())); }