private String getEmbeddedXML(ResultSet parentResultSet, EmbeddedElement element) { String xml = ""; if (element.embeddedPlaceholders.size() > 0) { xml = Utility.generateEmbeddedXMLbasedOnTemplate( parentResultSet, element.joinKeys, this.dataResultSets.get(element.name), element.template, element.valuePlaceholders); ResultSet resultSet = this.dataResultSets.get(element.name); for (String embeddedName : element.embeddedPlaceholders) { EmbeddedElement embeddedElement = element.embeddedElementMap.get(embeddedName); String embeddedXML = this.getEmbeddedXML(resultSet, embeddedElement); xml = Utility.replace(xml, "==" + embeddedName + "==\n", embeddedXML); } } else { xml = Utility.generateEmbeddedXMLbasedOnTemplate( parentResultSet, element.joinKeys, this.dataResultSets.get(element.name), element.template, element.valuePlaceholders); } return xml; }
/** @return Resolved string representation */ public final String toString(ConstantPool constant_pool) { String inner_class_name, outer_class_name, inner_name, access; inner_class_name = constant_pool.getConstantString(inner_class_index, Constants.CONSTANT_Class); inner_class_name = Utility.compactClassName(inner_class_name); if (outer_class_index != 0) { outer_class_name = constant_pool.getConstantString(outer_class_index, Constants.CONSTANT_Class); outer_class_name = Utility.compactClassName(outer_class_name); } else { outer_class_name = "<not a member>"; } if (inner_name_index != 0) { inner_name = ((ConstantUtf8) constant_pool.getConstant(inner_name_index, Constants.CONSTANT_Utf8)) .getBytes(); } else { inner_name = "<anonymous>"; } access = Utility.accessToString(inner_access_flags, true); access = access.equals("") ? "" : (access + " "); return "InnerClass:" + access + inner_class_name + "(\"" + outer_class_name + "\", \"" + inner_name + "\")"; }
/* * (non-Javadoc) * * @see * org.tempuri.ITestService#generateLoadWithResponseData(java.lang.Integer * refID ,)javax.xml.datatype.Duration sleepTime ,)byte[] inputData * ,)java.lang.Integer outputDataSize )* */ public org.datacontract.schemas._2004._07.services.StatisticInfo generateLoadWithResponseData( java.lang.Integer refID, javax.xml.datatype.Duration sleepTime, byte[] inputData, java.lang.Integer outputDataSize) { ServiceContext.Logger.traceEvent(Level.ALL, "Executing operation generateLoadWithResponseData"); try { StatisticInfo info = new StatisticInfo(); info.setRefID(refID); info.setStartTime(Utility.getXMLCurrentTime()); if (inputData != null) { for (byte b : inputData) { System.out.print(b); } } Thread.sleep(sleepTime.getTimeInMillis(new Date())); String instanceid = System.getenv(EnvVarNames.CCP_TASKINSTANCEID); String taskid = System.getenv(EnvVarNames.CCP_TASKID); if (Utility.isNullOrEmpty(instanceid)) instanceid = "0"; if (Utility.isNullOrEmpty(taskid)) taskid = "0"; if (instanceid.equals("0")) info.setInstanceId(svcObjFact.createStatisticInfoInstanceId(taskid)); else info.setInstanceId(svcObjFact.createStatisticInfoInstanceId(taskid + "." + instanceid)); info.setEndTime(Utility.getXMLCurrentTime()); return info; } catch (java.lang.Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
@After public void cleanUp() throws Exception { if (Utility.isProjExist(Messages.projCache)) { Utility.selProjFromExplorer(Messages.projCache).select(); Utility.deleteSelectedProject(); } }
public BranchTO[] getAllBranchByCountry(String countryId) { PreparedStatement pstmt = null; Connection con = null; ResultSet rs = null; BranchTO branchTO = null; ArrayList<BranchTO> branchList = new ArrayList<BranchTO>(); try { con = DAOFactory.getInstance().getConnection(Connection.TRANSACTION_READ_UNCOMMITTED); pstmt = con.prepareStatement(SQLConstants.LIST_BRANCH_BY_COUNTRY_SQL); pstmt.setInt(1, Integer.parseInt(countryId)); rs = pstmt.executeQuery(); while (rs.next()) { branchTO = new BranchTO(); branchTO.setId(rs.getString("id")); branchTO.setCode(Utility.trim(rs.getString("code"))); branchTO.setName(Utility.trim(rs.getString("name"))); branchTO.setStatus(Utility.trim(rs.getString("status"))); branchList.add(branchTO); } return (BranchTO[]) branchList.toArray(new BranchTO[0]); } catch (SQLException e) { throw new DataException(e.getMessage()); } catch (NamingException e) { throw new DataException(e.getMessage()); } finally { Utility.closeAll(null, pstmt, con); } }
public boolean tryDamageSkill(String rem, String cut, String output) { if (cut.length() > 0) if (rem.indexOf(cut) == 0) { rem = rem.substring(cut.length(), rem.length()); rem = Utility.clearWhiteSpace(rem); } target = owner.getRoom().findEntity(owner, rem); if ((target == null) && (owner.getPlayerState() == Utility.PSTATE_FIGHTING)) target = owner.getTarget(); if (target == null) { owner.echo(output); return false; } if (!Combat.canAttack(owner, target, false, true)) return false; tn = target.getName(); Tn = target.getPName(); ty = Utility.possessive(tn); Ty = Utility.possessive(Tn); return true; }
@Test // (Test Cases for 1.8) test case 4 public void testInvalidCacheSizeOKPressed() throws Exception { Utility.createProject(Messages.projCache); SWTBotShell propShell = Utility.selCacheUsingCnxtMenu(Messages.projCache, Messages.role1); wabot.checkBox().select(); // Cache size = 0 // typeText and setting focus on OK is IMP. wabot.textWithLabel(Messages.cachScaleLbl).setText(""); wabot.textWithLabel(Messages.cachScaleLbl).typeText("0"); wabot.button("OK").setFocus(); wabot.button("OK").click(); SWTBotShell errorShell = wabot.shell(Messages.cachPerErrTtl).activate(); Boolean zeroErr = errorShell.getText().equals(Messages.cachPerErrTtl); wabot.button("OK").click(); // Cache size < 0 i.e. Negative wabot.textWithLabel(Messages.cachScaleLbl).setText(""); wabot.textWithLabel(Messages.cachScaleLbl).typeText("-2"); wabot.button("OK").setFocus(); wabot.button("OK").click(); errorShell = wabot.shell(Messages.cachPerErrTtl).activate(); Boolean negErr = errorShell.getText().equals(Messages.cachPerErrTtl); wabot.button("OK").click(); // Cache size > 100 wabot.textWithLabel(Messages.cachScaleLbl).setText(""); wabot.textWithLabel(Messages.cachScaleLbl).typeText("105%"); wabot.button("OK").setFocus(); wabot.button("OK").click(); errorShell = wabot.shell(Messages.cachPerErrTtl).activate(); Boolean grtErr = errorShell.getText().equals(Messages.cachPerErrTtl); wabot.button("OK").click(); assertTrue("testInvalidCacheSizeOKPressed", zeroErr && negErr && grtErr); propShell.close(); }
public void reInitFragment() { mLayout.setVisibility(View.VISIBLE); mTxtDuration.setVisibility(View.GONE); mTxtTitle.setText(Utility.sMovieObject.Title); mTxtOverview.setText(Utility.sMovieObject.Overview); mTxtVoteAverage.setText(Utility.sMovieObject.VoteAverage + "/10"); try { mTxtReleaseDate.setText(Utility.sMovieObject.ReleaseDate.split("-")[0]); } catch (Exception e) { } mTxtReviews.setText(""); lstTrailersUrl.clear(); lstReviewsContent.clear(); lstTrailersNames.clear(); adpTrailersUrl.notifyDataSetChanged(); configListViewHeight(lstTrailers); if (mUtility.isMovieExist(Utility.sMovieObject.Id)) { imgPoster.setImageBitmap(mUtility.getImageBitmap(Utility.sMovieObject.MoviePoster)); btnFavorite.setChecked(true); } else { Picasso.with(getActivity()) .load(mUtility.IMAGE_URL + Utility.sMovieObject.MoviePoster) .placeholder(getContext().getResources().getDrawable(R.drawable.imgdefaultmovie)) .error(getContext().getResources().getDrawable(R.drawable.imgdefaultmovie)) .into(imgPoster); btnFavorite.setChecked(false); } new FetchAttachments().execute(MOVIE_INFO); }
private void updateEmptyView() { if (mForecastAdapter.getItemCount() == 0) { TextView tv = (TextView) getView().findViewById(R.id.recyclerview_forecast_empty); if (null != tv) { // if cursor is empty, why? do we have an invalid location int message = R.string.empty_forecast_list; @SunshineSyncAdapter.LocationStatus int location = Utility.getLocationStatus(getActivity()); switch (location) { case SunshineSyncAdapter.LOCATION_STATUS_SERVER_DOWN: message = R.string.empty_forecast_list_server_down; break; case SunshineSyncAdapter.LOCATION_STATUS_SERVER_INVALID: message = R.string.empty_forecast_list_server_error; break; case SunshineSyncAdapter.LOCATION_STATUS_INVALID: message = R.string.empty_forecast_list_invalid_location; break; default: if (!Utility.isNetworkAvailable(getActivity())) { message = R.string.empty_forecast_list_no_network; } } tv.setText(message); } } }
static ArrayList<UploadedCaption> fromFileSorted(long steamID, String packageName) { FileInputStream stream; try { stream = new FileInputStream(filePath(steamID, packageName)); } catch (FileNotFoundException e) { return null; } try { @SuppressWarnings("resource") int size = (new LittleEndianDataInputStream(stream)).readInt(); if (size < 0) { Utility.closeCloseable(stream); return null; } ArrayList<UploadedCaption> list = new ArrayList<UploadedCaption>(size); while (size-- > 0) { list.add(new UploadedCaption(stream)); } Utility.closeCloseable(stream); // Even though the list is sorted when saved, let's sort it again in case of // manipulation/corruption Collections.sort(list, new UploadedCaptionComparator()); return list; } catch (IOException e) { Utility.closeCloseable(stream); return null; } }
@SuppressWarnings("resource") static boolean toFile(ArrayList<UploadedCaption> list, long steamID, String packageName) { FileOutputStream stream; try { stream = new FileOutputStream(filePath(steamID, packageName)); } catch (FileNotFoundException e) { return false; } @SuppressWarnings("unchecked") ArrayList<UploadedCaption> newList = (ArrayList<UploadedCaption>) (list.clone()); Collections.sort(newList, new UploadedCaptionComparator()); int size = newList.size(); try { (new LittleEndianDataOutputStream(stream)).writeInt(size); Iterator<UploadedCaption> iterator = newList.iterator(); while (size-- > 0) { iterator.next().writeToStream(stream); } stream.flush(); Utility.closeCloseable(stream); return true; } catch (IOException e) { Utility.closeCloseable(stream); return false; } }
/** * 创建更新激活码 * * @param model * 激活码 * @return 激活码编号 */ public int createUpdate(wh.game.model.ActiveCode model) throws Exception{ Map<String, Object> inParameters = new HashMap<String, Object>(); inParameters.put("ActiveCodeId", model.getActiveCodeId()); inParameters.put("GameId", model.getGameId()); inParameters.put("ServerId", model.getServerId()); inParameters.put("Name", model.getName()); inParameters.put("Code", model.getCode()); inParameters.put("ActiveCodeType", model.getActiveCodeType()); inParameters.put("CreateDate", Utility.getSqlDate(model.getCreateDate())); inParameters.put("ModifyDate", Utility.getSqlDate(model.getModifyDate())); inParameters.put("Status", model.getStatus()); inParameters.put("UsedType", model.getUsedType()); OutParameters outParameters = new OutParameters(); outParameters.putOutParmType("ErrNo", java.sql.Types.INTEGER); outParameters.putOutParmType("ErrMsg", java.sql.Types.NVARCHAR); int parasCount = inParameters.size() + outParameters.getOutParmTypes().size(); StringBuilder sbBuilder = new StringBuilder(); for (int i = 0; i < parasCount; i++) { if (0 == i) { sbBuilder.append("?"); } else { sbBuilder.append(",?"); } } int retValue = SQLHelper.runProcedureNonQuery(Config.CONNECTION_STRING_ULD, "{? = call WH_Game_ActiveCode_CreateUpdate(" + sbBuilder.toString() + ")}", inParameters, outParameters); int errNo = Integer.valueOf(outParameters.getOutParmValue("ErrNo").toString()); String errMsg = outParameters.getOutParmValue("ErrMsg").toString(); MyErr.checkErr(errNo, errMsg); return retValue; }
public void testReadXMLGraph() throws javax.xml.bind.JAXBException, org.xml.sax.SAXException, java.io.IOException { ProvDeserialiser deserial = ProvDeserialiser.getThreadProvDeserialiser(); Document c = deserial.deserialiseDocument(new File("../prov-xml/target/pc1-full.xml")); Utility u = new Utility(); String[] schemaFiles = new String[1]; schemaFiles[0] = "../prov-xml/src/test/resources/pc1.xsd"; // TODO: now failing because of QName // deserial.validateDocument(schemaFiles,new File("../prov-xml/target/pc1-full.xml")); // String s=u.convertBeanToASN(c); // System.out.println(s); ProvSerialiser serial = ProvSerialiser.getThreadProvSerialiser(); c.setNamespace(Namespace.gatherNamespaces(c)); Document c2 = (Document) u.convertJavaBeanToJavaBean(c, pFactory); c2.setNamespace(c.getNamespace()); Namespace.withThreadNamespace(c2.getNamespace()); serial.serialiseDocument(new File("target/pc1-full-2.xml"), c2, true); }
public void dump(long lMethod) { Log.log( "\ttag = 0x" + Utility.toHexString(tag) + " (" + OptionalParameterTag.toString(tag) + ")", 0x100000000000000L | lMethod); Log.log("\tlength = " + length, 0x100000000000000L | lMethod); Log.log("\tvalue(binary) = 0x" + Utility.toHexString(value), 0x100000000000000L | lMethod); }
private String formatHighLows(double high, double low) { String highLowStr = Utility.convertTempToSystemUnit(high, getContext()) + "/" + Utility.convertTempToSystemUnit(low, getContext()); return highLowStr; }
@Override protected Void doInBackground(Cursor... params) { Cursor cursor = params[0]; cursor.moveToPosition(0); double high = cursor.getDouble(ForecastFragment.COL_WEATHER_MAX_TEMP); String max = Utility.formatTemperature(getActivity(), high); double low = cursor.getDouble(ForecastFragment.COL_WEATHER_MIN_TEMP); String min = Utility.formatTemperature(getActivity(), low); int weatherId = cursor.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID); Bitmap weatherIconBitmap = null; try { weatherIconBitmap = Glide.with(getActivity()) .load(Utility.getArtUrlForWeatherCondition(getActivity(), weatherId)) .asBitmap() .into(100, 100) . // Width and height get(); ((TodayDataCallback) getActivity()).onTodayDataLoaded(max, min, weatherIconBitmap); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; }
private void sendPurchaseHit() { Product product = new Product() .setName("dinner") .setPrice(5) .setVariant(thisDinner) .setId(Utility.getDinnerId(thisDinner)) .setQuantity(1); ProductAction productAction = new ProductAction(ProductAction.ACTION_PURCHASE) .setTransactionId(Utility.getUniqueTransactionId(Utility.getDinnerId(thisDinner))); Tracker tracker = ((MyApplication) getApplication()).getTracker(); tracker.send( new HitBuilders.EventBuilder() .setCategory("Shopping steps") .setAction("Purchase") .setLabel(thisDinner) .addProduct(product) .setProductAction(productAction) .build()); }
private void doReportFinish() { if (DEBUG) Log.d(TAG, "doReportFinish"); try { JSONObject jdata = new JSONObject(); jdata .put("action", "report finish") .put("priority", 10) .put("report_counts", mReportCounts) .put("reporter", Utility.getMyToken(this)) .put("delay_while_idle", false); JSONObject root = new JSONObject(); root.put("to", mReturnAddress); root.put("data", jdata); Utility.sendMessageAsync( this, root.toString(), new Utility.AsyncTaskCallback() { @Override void onPostExecute() { stopSelf(); } }); } catch (JSONException e) { e.printStackTrace(); } }
// Performs a binary search to satisfy the Wolfe conditions // returns alpha where next x =should be x0 + alpha*d // guarantees convergence as long as search direction is bounded away from being orthogonal with // gradient // x0 is starting point, d is search direction, alpha is starting step size, maxit is max // iterations // c1 and c2 are the constants of the Wolfe conditions (0.1 and 0.9 can work) // uses an approximate directional gradient since a true gradient is not defined for the optical // flow error function public double stepSize(double[] x0, double[] d, double alpha, int maxit, double c1, double c2) { // get error and gradient at starting point double fx0 = error(x0); double gx0 = dotGradient(x0, d); // bound the solution double alphaL = 0; double alphaR = 100; for (int iter = 1; iter <= maxit; iter++) { double[] xp = Utility.add(x0, Utility.scale(d, alpha)); // get the point at this alpha double erroralpha = error(xp); // get the error at that point if (erroralpha >= fx0 + alpha * c1 * gx0) { // if error is not sufficiently reduced alphaR = alpha; // move halfway between current alpha and lower alpha alpha = (alphaL + alphaR) / 2.0; } else { // if error is sufficiently decreased double slopealpha = dotGradient(xp, d); // then get slope along search direction if (slopealpha <= c2 * Math.abs(gx0)) { // if slope sufficiently closer to 0 return alpha; // then this is an acceptable point } else if (slopealpha >= c2 * gx0) { // if slope is too steep and positive then go to the left alphaR = alpha; // move halfway between current alpha and lower alpha alpha = (alphaL + alphaR) / 2; } else { // if slope is too steep and negative then go to the right of this alpha alphaL = alpha; // move halfway between current alpha and upper alpha alpha = (alphaL + alphaR) / 2; } } } // if ran out of iterations then return the best thing we got return alpha; }
protected void onPostExecute(String result) { try { JSONObject jsonObject = new JSONObject(result); JSONArray fileArray; Object status = jsonObject.get("estado"); Object message = jsonObject.get("mensaje"); if (status.equals("ok")) { Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show(); Log.i("Search", message.toString()); Utility.appendToInfoLog("Search", message.toString()); Log.d("Search", jsonObject.toString()); Utility.appendToDebugLog("Search", jsonObject.toString()); if (jsonObject.has("archivos")) { fileArray = jsonObject.getJSONArray("archivos"); for (int i = 0; i < fileArray.length(); i++) { String filePath = fileArray.getString(i); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); filesList.add(fileName); } } else { filesList.add("No results for your search"); } ArrayAdapter<String> files = new ArrayAdapter<>(getApplicationContext(), R.layout.list_item, filesList); lv.setAdapter(files); } else { Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show(); Log.e("Search", message.toString()); Utility.appendToErrorLog("Search", message.toString()); } } catch (Exception e) { Log.e("Search", e.getLocalizedMessage()); Utility.appendToErrorLog("Search", e.getLocalizedMessage()); } }
@Test // (Test Cases for 1.8) test case 6 public void testNtNumericCacheSizeOKPressed() throws Exception { Utility.createProject(Messages.projCache); SWTBotShell propShell = Utility.selCacheUsingCnxtMenu(Messages.projCache, Messages.role1); wabot.checkBox().select(); // Cache size = alphabet // typeText and setting focus on OK is IMP. wabot.textWithLabel(Messages.cachScaleLbl).setText(""); wabot.textWithLabel(Messages.cachScaleLbl).typeText("ab"); wabot.button("OK").setFocus(); wabot.button("OK").click(); SWTBotShell errorShell = wabot.shell(Messages.cachPerErrTtl).activate(); Boolean alphabtErr = errorShell.getText().equals(Messages.cachPerErrTtl); wabot.button("OK").click(); // Cache size = special character wabot.textWithLabel(Messages.cachScaleLbl).setText(""); wabot.textWithLabel(Messages.cachScaleLbl).typeText("#*"); wabot.button("OK").setFocus(); wabot.button("OK").click(); errorShell = wabot.shell(Messages.cachPerErrTtl).activate(); Boolean splCharErr = errorShell.getText().equals(Messages.cachPerErrTtl); wabot.button("OK").click(); assertTrue("testNtNumericCacheSizeOKPressed", alphabtErr && splCharErr); propShell.close(); }
public String getSearchFiles(String URL) { StringBuilder stringBuilder = new StringBuilder(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(URL); JSONObject json = new JSONObject(); try { json.put("mail", email); httpGet.setEntity(new StringEntity(json.toString(), "UTF-8")); httpGet.setHeader("Content-Type", "application/json"); httpGet.setHeader("Accept-Encoding", "application/json"); HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } inputStream.close(); } else { Log.e("Search", "status code: " + statusCode); Utility.appendToErrorLog("Search", "status code: " + statusCode); } } catch (Exception e) { Log.e("Search", e.getLocalizedMessage()); Utility.appendToErrorLog("Search", e.getLocalizedMessage()); } return stringBuilder.toString(); }
public boolean updateBranch(BranchTO branchTO) { PreparedStatement pstmt = null; Connection con = null; int result; try { con = DAOFactory.getInstance().getConnection(Connection.TRANSACTION_READ_UNCOMMITTED); pstmt = con.prepareStatement(SQLConstants.UPDATE_BRANCH_SQL); pstmt.setString(1, Utility.trim(branchTO.getName())); pstmt.setString(2, Utility.trim(branchTO.getCountry().getId())); pstmt.setString(3, Utility.trim(branchTO.getStatus())); pstmt.setInt(4, 1); pstmt.setString(5, Utility.trim(branchTO.getId())); result = pstmt.executeUpdate(); if (result > 0) { return true; } else { return false; } } catch (SQLException e) { throw new DataException(e.getMessage()); } catch (NamingException e) { throw new DataException(e.getMessage()); } finally { Utility.closeAll(null, pstmt, con); } }
public void checkSessionLogout() throws Exception { uti.writeAsteriskLog("- SYSTE - Check DateTime Agent unLogout"); String date = uti.getDate(); String sql = "SELECT * FROM login_action WHERE CAST(datetime_login AS DATE) >= '" + date + "'"; ResultSet rs = sqlQuery(sql); String datenow = uti.getDatetime(); while (rs.next()) { String datelogout = String.valueOf(rs.getObject("datetime_logout")); if (datelogout.equalsIgnoreCase("null")) { String agentid = String.valueOf(rs.getObject("agent_id")); String iface = String.valueOf(rs.getObject("interface")); String queue = String.valueOf(rs.getObject("queue")); String session = rs.getString("session"); updateStatus(agentid, "NULL", "NULL"); logoutAction(session, agentid); uti.writeAsteriskLog( "- SYSTE - Update datetime agent unlogout\t" + agentid + "\t" + session); System.out.println("update success logout\t" + session); // sql = "UPDATE login_action SET datetime_logout ='"+datenow+"'" // + " WHERE session = '"+session+"'" ; // int rs2 = sqlExecute(sql); // if(rs2 != 0) // uti.writeAsteriskLog("- SYSTE - Update datetime agent // unlogout\t"+agentid+"\t"+session); // System.out.println("update success\t"+session); // String sql2 = "UPDATE agent_status SET interface =null,queue=null // WHERE agent_id = '"+agentid+"'" ; // rs2 = sqlExecute(sql2); } } }
public void printVariable() { Utility.Dprintc("VARIABLE " + varID + " ", 0); for (int j = 0; j < domain.length; j++) { Utility.Dprintc(domain[j].toString() + " ", 0); } Utility.Dprint("", 0); }
/** * @param config * @param statFilePathParam * @param delim * @param idOrdinals * @param stats * @param keyedStats * @throws IOException */ private void loadMedianStat( Configuration config, String statFilePathParam, String delim, int[] idOrdinals, Map<Integer, Double> stats, Map<String, Map<Integer, Double>> keyedStats) throws IOException { List<String> lines = Utility.getFileLines(config, statFilePathParam); for (String line : lines) { String[] items = line.split(delim); if (null != idOrdinals) { // with IDs String compId = Utility.join(items, 0, idOrdinals.length, delim); Map<Integer, Double> medians = keyedStats.get(compId); if (null == medians) { medians = new HashMap<Integer, Double>(); keyedStats.put(compId, medians); } medians.put( Integer.parseInt(items[idOrdinals.length]), Double.parseDouble(items[idOrdinals.length + 1])); } else { // without IDs stats.put(Integer.parseInt(items[0]), Double.parseDouble(items[1])); } } }
@Override public void OnExiting(Sender sender, SOAEventArg soaEventArg) { try { Thread.sleep(exitDelay); String onAzureEnv = System.getenv("CCP_OnAzure"); if (!Utility.isNullOrEmpty(onAzureEnv) && !onAzureEnv.equals("1") && Utility.isNullOrEmpty(logPath)) { String taskInfo = String.format( "%s.%s.%s", System.getenv(EnvVarNames.CCP_JOBID), System.getenv(EnvVarNames.CCP_TASKID), System.getenv(EnvVarNames.CCP_TASKINSTANCEID)); writeLog( logPath + "\\CCP_AITest_Trace_" + String.valueOf(jobid), refID, "[Request] %s%%%s%%Svchost called.", Utility.getCurrentTime(), taskInfo); } System.out.format("[Exit] %s: GracefulExitEvent called.%n", Utility.getCurrentTime()); info.setOnExitCalled(true); } catch (Exception e) { e.printStackTrace(); } }
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data.moveToFirst()) { detailString = convertCursorRowToUXFormat(data); if (shareProvider != null) { shareProvider.setShareIntent(createForecastShareIntent()); } mWeatherId = data.getInt(COL_WEATHER_ID); long date = data.getLong(ForecastFragment.COL_WEATHER_DATE); // POPULATE THE text views mDay.setText(Utility.getDayName(getActivity(), date)); mDate.setText(Utility.getFormattedMonthDay(getActivity(), date)); mHigh.setText( getString(R.string.format_degrees, data.getFloat(ForecastFragment.COL_WEATHER_MAX_TEMP))); mLow.setText( getString(R.string.format_degrees, data.getFloat(ForecastFragment.COL_WEATHER_MIN_TEMP))); mHumidity.setText(getString(R.string.format_humidity, data.getFloat(COL_HUMIDITY))); mPressure.setText(getString(R.string.format_pressure, data.getFloat(COL_PRESSURE))); mIcon.setImageResource(Utility.weatherCodeToArtPath(mWeatherId)); float windSpeed = data.getFloat(COL_WIND_SPEED); String windDirection = getWindDirection(data.getFloat(COL_DEGREES)); mWind.setText(getString(R.string.format_wind_kmh, windSpeed, windDirection)); if (mCompass != null) { mCompass.setAngle(degreesToRadians(data.getFloat(COL_DEGREES))); } mDescription.setText(data.getString(ForecastFragment.COL_WEATHER_DESC)); } }
/** Unit test for TupleDesc.combine() */ @Test public void combine() { TupleDesc td1, td2, td3; td1 = Utility.getTupleDesc(1, "td1"); td2 = Utility.getTupleDesc(2, "td2"); // test td1.combine(td2) td3 = TupleDesc.merge(td1, td2); assertEquals(3, td3.numFields()); assertEquals(3 * Type.INT_TYPE.getLen(), td3.getSize()); for (int i = 0; i < 3; ++i) assertEquals(Type.INT_TYPE, td3.getFieldType(i)); assertEquals(combinedStringArrays(td1, td2, td3), true); // test td2.combine(td1) td3 = TupleDesc.merge(td2, td1); assertEquals(3, td3.numFields()); assertEquals(3 * Type.INT_TYPE.getLen(), td3.getSize()); for (int i = 0; i < 3; ++i) assertEquals(Type.INT_TYPE, td3.getFieldType(i)); assertEquals(combinedStringArrays(td2, td1, td3), true); // test td2.combine(td2) td3 = TupleDesc.merge(td2, td2); assertEquals(4, td3.numFields()); assertEquals(4 * Type.INT_TYPE.getLen(), td3.getSize()); for (int i = 0; i < 4; ++i) assertEquals(Type.INT_TYPE, td3.getFieldType(i)); assertEquals(combinedStringArrays(td2, td2, td3), true); }
// get the caption for the loop's visual representation // the caption is an abbreviated form of the code // the caption appears in the upper-left corner of the loop public String getCaption() { String caption = ""; switch (type) { case LOOP_TYPE_REPETITIONS: if (!numWarmups.equals("0")) { caption += numWarmups + " " + Utility.wordForm(numWarmups, "warmups") + " + "; if (sync) caption += "sync + "; } caption += numReps + " " + Utility.wordForm(numReps, "reps"); return caption; case LOOP_TYPE_FOR_EACH: caption = sequenceName + " in "; for (int i = 0; i < sequences.size(); i++) { String sequence = (String) sequences.elementAt(i); if (i > 0) caption += ", "; caption += "{" + sequence + "}"; } return caption; case LOOP_TYPE_TIMED: return toCode(); default: assert false; return ""; } }