List of usage examples for android.util Log DEBUG
int DEBUG
To view the source code for android.util Log DEBUG.
Click Source Link
From source file:org.swiftp.server.ProxyConnector.java
@Override public void run() { myLog.i("In ProxyConnector.run()"); setProxyState(State.CONNECTING); try {/*from w ww . j av a 2 s . c o m*/ String candidateProxies[] = getProxyList(); for (String candidateHostname : candidateProxies) { hostname = candidateHostname; commandSocket = newAuthedSocket(hostname, Defaults.REMOTE_PROXY_PORT); if (commandSocket == null) { continue; } commandSocket.setSoTimeout(0); // 0 == forever // commandSocket.setKeepAlive(true); // Now that we have authenticated, we want to start the command session so // we can // be notified of pending control sessions. JSONObject request = makeJsonRequest("start_command_session"); response = sendRequest(commandSocket, request); if (response == null) { myLog.i("Couldn't create proxy command session"); continue; // try next server } if (!response.has("prefix")) { myLog.l(Log.INFO, "start_command_session didn't receive a prefix in response"); continue; // try next server } prefix = response.getString("prefix"); response = null; // Indicate that response is free for other use myLog.l(Log.INFO, "Got prefix of: " + prefix); break; // breaking with commandSocket != null indicates success } if (commandSocket == null) { myLog.l(Log.INFO, "No proxies accepted connection, failing."); setProxyState(State.UNREACHABLE); return; } setProxyState(State.CONNECTED); preferServer(hostname); inputStream = commandSocket.getInputStream(); out = commandSocket.getOutputStream(); int numBytes; byte[] bytes = new byte[IN_BUF_SIZE]; // spawnQuotaRequester().start(); while (true) { myLog.d("to proxy read()"); numBytes = inputStream.read(bytes); incrementProxyUsage(numBytes); myLog.d("from proxy read()"); JSONObject incomingJson = null; if (numBytes > 0) { String responseString = new String(bytes, ENCODING); incomingJson = new JSONObject(responseString); if (incomingJson.has("action")) { // If the incoming JSON object has an "action" field, then it is a // request, and not a response incomingCommand(incomingJson); } else { // If the incoming JSON object does not have an "action" field, // then // it is a response to a request we sent earlier. // If there's an object waiting for a response, then that object // will be referenced by responseWaiter. if (responseWaiter != null) { if (response != null) { myLog.l(Log.INFO, "Overwriting existing cmd session response"); } response = incomingJson; responseWaiter.interrupt(); } else { myLog.l(Log.INFO, "Response received but no responseWaiter"); } } } else if (numBytes == 0) { myLog.d("Command socket read 0 bytes, looping"); } else { // numBytes < 0 myLog.l(Log.DEBUG, "Command socket end of stream, exiting"); if (proxyState != State.DISCONNECTED) { // Set state to FAILED unless this was an intentional // socket closure. setProxyState(State.FAILED); } break; } } myLog.l(Log.INFO, "ProxyConnector thread quitting cleanly"); } catch (IOException e) { myLog.l(Log.INFO, "IOException in command session: " + e); setProxyState(State.FAILED); } catch (JSONException e) { myLog.l(Log.INFO, "Commmand socket JSONException: " + e); setProxyState(State.FAILED); } catch (Exception e) { myLog.l(Log.INFO, "Other exception in ProxyConnector: " + e); setProxyState(State.FAILED); } finally { Globals.setProxyConnector(null); hostname = null; myLog.d("ProxyConnector.run() returning"); persistProxyUsage(); } }
From source file:com.redinput.datetimepickercompat.date.DayPickerView.java
/** * This moves to the specified time in the view. If the time is not already * in range it will move the list so that the first of the month containing * the time is at the top of the view. If the new time is already in view * the list will not be scrolled unless forceScroll is true. This time may * optionally be highlighted as selected as well. * /*w w w .j ava 2 s . c o m*/ * @param time * The time to move to * @param animate * Whether to scroll to the given time or just redraw at the * new location * @param setSelected * Whether to set the given time as selected * @param forceScroll * Whether to recenter even if the time is already * visible * @return Whether or not the view animated to the new location */ @SuppressLint("NewApi") public boolean goTo(CalendarDay day, boolean animate, boolean setSelected, boolean forceScroll) { // Set the selected day if (setSelected) { mSelectedDay.set(day); } mTempDay.set(day); final int position = (day.year - mController.getMinYear()) * SimpleMonthAdapter.MONTHS_IN_YEAR + day.month; View child; int i = 0; int top = 0; // Find a child that's completely in the view do { child = getChildAt(i++); if (child == null) { break; } top = child.getTop(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "child at " + (i - 1) + " has top " + top); } } while (top < 0); // Compute the first and last position visible int selectedPosition; if (child != null) { selectedPosition = getPositionForView(child); } else { selectedPosition = 0; } if (setSelected) { mAdapter.setSelectedDay(mSelectedDay); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "GoTo position " + position); } // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position != selectedPosition || forceScroll) { setMonthDisplayed(mTempDay); mPreviousScrollState = OnScrollListener.SCROLL_STATE_FLING; if (animate) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { smoothScrollToPositionFromTop(position, LIST_TOP_OFFSET, GOTO_SCROLL_DURATION); } else { postSetSelection(position); } return true; } else { postSetSelection(position); } } else if (setSelected) { setMonthDisplayed(mSelectedDay); } return false; }
From source file:com.example.android.jumpingjack.MainActivity.java
/** * Starts a timer to clear the flag FLAG_KEEP_SCREEN_ON. *//*from w ww . j a va 2s. c o m*/ private void renewTimer() { if (null != mTimer) { mTimer.cancel(); } mTimerTask = new TimerTask() { @Override public void run() { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Removing the FLAG_KEEP_SCREEN_ON flag to allow going to background"); } resetFlag(); } }; mTimer = new Timer(); mTimer.schedule(mTimerTask, SCREEN_ON_TIMEOUT_MS); }
From source file:it.sephiroth.android.library.bottomnavigation.BottomNavigation.java
@Override protected void onRestoreInstanceState(final Parcelable state) { log(TAG, INFO, "onRestoreInstanceState"); SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); defaultSelectedIndex = savedState.selectedIndex; log(TAG, Log.DEBUG, "defaultSelectedIndex: %d", defaultSelectedIndex); if (null != badgeProvider && null != savedState.badgeBundle) { badgeProvider.restore(savedState.badgeBundle); }// w w w .java 2 s . co m }
From source file:com.ibm.commerce.worklight.android.search.SearchSuggestionsProvider.java
/** * Retrieves the search suggestion JSON array and constructs the search suggestions list * For example, the JSON array would follow a similar structure, using a search on the * term 'dress':/*from w ww .j a v a 2 s . c o m*/ * * {'terms': * [ * {'dress':'766'}, * {'dress empire':'62'}, * {'dress empire waist':'62'}, * {'dress layered':'57'}, * ... * ] * } * * @param string The query term input into the search dialog * @return The list of search term suggestions */ private List<String> getSearchTermSuggestions(String query) { final String METHOD_NAME = CLASS_NAME + ".getSearchTermSuggestions"; boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG); if (loggingEnabled) { Log.d(METHOD_NAME, "ENTRY"); } List<String> suggestionList = null; if (query == null || query.equals("")) { return suggestionList; } WCHybridApplication wcHybridApp = WCHybridApplication.getInstance(); String requestUrl = wcHybridApp.getSearchSuggestionUrl(query).toString(); String suggestionJsonString = null; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIME_OUT); HttpClient httpClient = new DefaultHttpClient(httpParams); try { suggestionJsonString = httpClient.execute(new HttpGet(requestUrl), new BasicResponseHandler()); } catch (ClientProtocolException e) { Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage()); } catch (IOException e) { Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage()); } finally { httpClient.getConnectionManager().shutdown(); } if (suggestionJsonString != null && !suggestionJsonString.equals("")) { try { if (loggingEnabled) { Log.d(METHOD_NAME, "Suggestion JSON string: " + suggestionJsonString); } JSONObject json = new JSONObject(suggestionJsonString); JSONArray suggestions = json.getJSONArray("terms"); if (suggestions != null) { suggestionList = new ArrayList<String>(suggestions.length()); for (int i = 0; i < suggestions.length(); i++) { suggestionList.add(suggestions.getJSONObject(i).names().getString(0)); } } } catch (JSONException e) { Log.d(METHOD_NAME, "Error parsing search suggestion JSON: " + e.getLocalizedMessage()); } } if (loggingEnabled) { Log.d(METHOD_NAME, "EXIT"); } return suggestionList; }
From source file:com.samsung.spen.SpenPlugin.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Inside execute"); }/* w w w .j av a 2s .c o m*/ // sometimes, init is not called from initialize init(); // Do not allow apis if metadata is missing if (!pluginMetadata) { callbackContext.error("METADATA_MISSING"); Log.e(TAG, "Metadata is missing"); return false; } initContextDetails(callbackContext); final CallbackContext finalCallbackContext = callbackContext; mSpenState = isSpenFeatureEnabled(mActivity.getApplicationContext(), callbackContext); if (action.equals("isSupported")) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "Inside isSpenSupported"); } if (mSpenState == SPEN_AND_HAND_SUPPORTED) { callbackContext.success(SpenExceptionType.SPEN_AND_HAND_SUPPORTED.toString()); return true; } else if (mSpenState == ONLY_HAND_SUPPORTED) { callbackContext.success(SpenExceptionType.ONLY_HAND_SUPPORTED.toString()); // handled this in isSpenFeatureEnabled itself as it common // for many cases. } } else if (action.equals("launchSurfaceInline")) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "creating the spen surface inline"); } SpenTrayBarOptions options = createTrayBarOptions(args, Utils.SURFACE_INLINE, callbackContext); final SpenTrayBarOptions inlineOptions = options; if (inlineOptions != null && mSpenState != SPEN_INITILIZATION_ERROR) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { String id = inlineOptions.getId(); if (mSpenSurfaceViews.getSurfaceView(id) == null) { if (surfaceCount >= SpenSurfaceViews.MAX_SURFACE_COUNT) { SpenException.sendPluginResult(SpenExceptionType.MAX_SURFACE_LIMIT_REACHED, finalCallbackContext); } else { SPenSurfaceWithTrayBar mPaintViewTrayBar = null; mPaintViewTrayBar = new SPenSurfaceWithTrayBar(mContextParams, inlineOptions); mSpenSurfaceViews.addSurfaceView(id, mPaintViewTrayBar); surfaceCount++; if (!mSpenSurfaceViews.getSurfaceView(id).createSPenSurfaceWithTrayBar()) { mSpenSurfaceViews.removeSurfaceView(id); surfaceCount--; SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE, finalCallbackContext); } else { // finalCallbackContext.success(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, ""); pluginResult.setKeepCallback(true); finalCallbackContext.sendPluginResult(pluginResult); } } } else { SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_ALREADY_EXISTS, finalCallbackContext); } } }); } } else if (action.equals("launchSurfacePopup")) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "creating the spen surface popup"); } SpenTrayBarOptions options = createTrayBarOptions(args, Utils.SURFACE_POPUP, callbackContext); if (options != null && mSpenState != SPEN_INITILIZATION_ERROR) { String id = options.getId(); if (mSpenSurfaceViewsPopup.getSurfaceView(id) == null) { if (surfaceCount >= SpenSurfaceViews.MAX_SURFACE_COUNT) { SpenException.sendPluginResult(SpenExceptionType.MAX_SURFACE_LIMIT_REACHED, finalCallbackContext); } else { SPenSurfaceWithTrayBar mPaintViewTrayBar = null; mPaintViewTrayBar = new SPenSurfaceWithTrayBar(mContextParams, options); mSpenSurfaceViewsPopup.addSurfaceView(id, mPaintViewTrayBar); surfaceCount++; if (!mSpenSurfaceViewsPopup.getSurfaceView(id).createSPenSurfaceWithTrayBar()) { mSpenSurfaceViewsPopup.removeSurfaceView(id); surfaceCount--; SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE, finalCallbackContext); } else { PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, ""); pluginResult.setKeepCallback(true); finalCallbackContext.sendPluginResult(pluginResult); } } } else { mSpenSurfaceViewsPopup.getSurfaceView(id).changeSPenTrayBarOptions(options, mContextParams); mSpenSurfaceViewsPopup.getSurfaceView(id).openSPenSurfaceWithTrayBar(); } } } else if (action.equals("removeSurfaceInline")) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "removing SpenSurface Inline"); } String tempId = args.getString(ID); if (tempId != null) { tempId = tempId.trim(); if (tempId.length() > MAX_ID_LENGTH) { tempId = tempId.substring(0, MAX_ID_LENGTH); } } final String id = tempId; if (id == null || id.equals("") || id.equals("null")) { SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext); return false; } if (mSpenState != SPEN_INITILIZATION_ERROR) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mSpenSurfaceViews.getSurfaceView(id) != null) { surfaceCount--; mSpenSurfaceViews.getSurfaceView(id).removeSurface(); mSpenSurfaceViews.removeSurfaceView(id); finalCallbackContext.success(id); } else { SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_NOT_EXISTS, finalCallbackContext); } } }); } } else if (action.equals("removeSurfacePopup")) { if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) { Log.d(TAG, "removing SpenSurface Popup"); } String tempId = args.getString(ID); if (tempId != null) { tempId = tempId.trim(); if (tempId.length() > MAX_ID_LENGTH) { tempId = tempId.substring(0, MAX_ID_LENGTH); } } final String id = tempId; if (id == null || id.equals("") || id.equals("null")) { SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext); return false; } if (mSpenSurfaceViewsPopup.getSurfaceView(id) != null) { surfaceCount--; mSpenSurfaceViewsPopup.getSurfaceView(id).removeSurface(); mSpenSurfaceViewsPopup.removeSurfaceView(id); finalCallbackContext.success(id); } else { SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_NOT_EXISTS, finalCallbackContext); } } else { callbackContext.error(SpenExceptionType.ACTION_INVALID.toString()); return false; } return true; }
From source file:com.scvngr.levelup.core.util.LogManager.java
/** * Logs a message to the Android log.//w w w . jav a 2 s . co m * * @param logLevel {@link Log#VERBOSE}, {@link Log#DEBUG}, {@link Log#INFO}, {@link Log#WARN}, * or {@link Log#ERROR}. * @param message the message to be logged. This message is expected to be a format string if * messageFormatArgs is not null. * @param messageFormatArgs formatting arguments for the message, or null if the string is to be * handled without formatting. * @param err an optional error to log with a stacktrace. */ private static void logMessage(final int logLevel, @NonNull final String message, @Nullable final Object[] messageFormatArgs, @Nullable final Throwable err) { final String preppedMessage = formatMessage(message, messageFormatArgs); final StackTraceElement[] trace = Thread.currentThread().getStackTrace(); final String sourceClass = trace[STACKTRACE_SOURCE_FRAME_INDEX].getClassName(); final String sourceMethod = trace[STACKTRACE_SOURCE_FRAME_INDEX].getMethodName(); final String logcatLogLine = String.format(Locale.US, FORMAT, Thread.currentThread().getName(), sourceClass, sourceMethod, preppedMessage); switch (logLevel) { case Log.VERBOSE: { if (null == err) { Log.v(sLogTag, logcatLogLine); } else { Log.v(sLogTag, logcatLogLine, err); } break; } case Log.DEBUG: { if (null == err) { Log.d(sLogTag, logcatLogLine); } else { Log.d(sLogTag, logcatLogLine, err); } break; } case Log.INFO: { if (null == err) { Log.i(sLogTag, logcatLogLine); } else { Log.i(sLogTag, logcatLogLine, err); } break; } case Log.WARN: { if (null == err) { Log.w(sLogTag, logcatLogLine); } else { Log.w(sLogTag, logcatLogLine, err); } break; } case Log.ERROR: { if (null == err) { Log.e(sLogTag, logcatLogLine); } else { Log.e(sLogTag, logcatLogLine, err); } break; } case Log.ASSERT: { if (null == err) { Log.wtf(sLogTag, logcatLogLine); } else { Log.wtf(sLogTag, logcatLogLine, err); } break; } default: { throw new AssertionError(); } } }
From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;/*from ww w . ja va 2 s . co m*/ int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:com.joptimizer.optimizers.BasicPhaseIPDM.java
public DoubleMatrix1D findFeasibleInitialPoint() throws Exception { Log.d(MainActivity.JOPTIMIZER_LOGTAG, "findFeasibleInitialPoint"); OptimizationRequest or = new OptimizationRequest(); //objective function: s DoubleMatrix1D C = F1.make(dim);/* w ww . ja v a 2 s .co m*/ C.set(dim - 1, 1.); LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(C.toArray(), 0); or.setF0(objectiveFunction); or.setToleranceFeas(originalProblem.getToleranceFeas()); or.setTolerance(originalProblem.getTolerance()); // Inquality constraints: fi(X)-s ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[originalProblem .getFi().length]; for (int i = 0; i < inequalities.length; i++) { final ConvexMultivariateRealFunction originalFi = originalProblem.getFi()[i]; ConvexMultivariateRealFunction fi = new ConvexMultivariateRealFunction() { public double value(double[] Y) { DoubleMatrix1D y = DoubleFactory1D.dense.make(Y); DoubleMatrix1D X = y.viewPart(0, originalDim); return originalFi.value(X.toArray()) - y.get(dim - 1); } public double[] gradient(double[] Y) { DoubleMatrix1D y = DoubleFactory1D.dense.make(Y); DoubleMatrix1D X = y.viewPart(0, originalDim); DoubleMatrix1D origGrad = F1.make(originalFi.gradient(X.toArray())); DoubleMatrix1D ret = F1.make(1, -1); ret = F1.append(origGrad, ret); return ret.toArray(); } public double[][] hessian(double[] Y) { DoubleMatrix1D y = DoubleFactory1D.dense.make(Y); DoubleMatrix1D X = y.viewPart(0, originalDim); double[][] originalFiHess = originalFi.hessian(X.toArray()); if (originalFiHess == FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER) { return FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER; } else { DoubleMatrix2D origHess = (originalFiHess != FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER) ? F2.make(originalFi.hessian(X.toArray())) : F2.make(X.size(), X.size()); DoubleMatrix2D[][] parts = new DoubleMatrix2D[][] { { origHess, null }, { null, F2.make(1, 1) } }; return F2.compose(parts).toArray(); } } public int getDim() { return dim; } }; inequalities[i] = fi; } or.setFi(inequalities); // Equality constraints: add a final zeroes column DoubleMatrix2D AEorig = originalProblem.getA(); DoubleMatrix1D BEorig = originalProblem.getB(); if (AEorig != null) { DoubleMatrix2D zeroCols = F2.make(AEorig.rows(), 1); DoubleMatrix2D[][] parts = new DoubleMatrix2D[][] { { AEorig, zeroCols } }; DoubleMatrix2D AE = F2.compose(parts); DoubleMatrix1D BE = BEorig.copy(); or.setA(AE.toArray()); or.setB(BE.toArray()); } //initial point DoubleMatrix1D X0 = originalProblem.getNotFeasibleInitialPoint(); if (X0 == null) { if (AEorig != null) { X0 = findOneRoot(AEorig.toArray(), BEorig.toArray()); } else { X0 = F1.make(originalProblem.getDim(), 1. / originalProblem.getDim()); } } //check primal norm if (AEorig != null) { DoubleMatrix1D originalRPriX0 = AEorig.zMult(X0, BEorig.copy(), 1., -1., false); double norm = Math.sqrt(ALG.norm2(originalRPriX0)); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "norm: " + norm); if (norm > originalProblem.getToleranceFeas()) { throw new Exception("The initial point for Basic Phase I Method must be equalities-feasible"); } } DoubleMatrix1D originalFiX0 = originalProblem.getFi(X0); //lucky strike? int maxIneqIndex = Utils.getMaxIndex(originalFiX0.toArray()); if (originalFiX0.get(maxIneqIndex) + originalProblem.getTolerance() < 0) { //the given notFeasible starting point is in fact already feasible return X0; } //DoubleMatrix1D initialPoint = F1.make(1, -Double.MAX_VALUE); DoubleMatrix1D initialPoint = F1.make(1, Math.sqrt(originalProblem.getToleranceFeas())); initialPoint = F1.append(X0, initialPoint); for (int i = 0; i < originalFiX0.size(); i++) { //initialPoint.set(dim-1, Math.max(initialPoint.get(dim-1), originalFiX0.get(i)+Math.sqrt(originalProblem.getToleranceFeas()))); initialPoint.set(dim - 1, Math.max(initialPoint.get(dim - 1), originalFiX0.get(i) * Math.pow(originalProblem.getToleranceFeas(), -0.5))); } or.setInitialPoint(initialPoint.toArray()); //optimization PrimalDualMethod opt = new PhaseIPrimalDualMethod(); opt.setOptimizationRequest(or); if (opt.optimize() == OptimizationResponse.FAILED) { throw new Exception("Failed to find an initial feasible point"); } OptimizationResponse response = opt.getOptimizationResponse(); DoubleMatrix1D sol = F1.make(response.getSolution()); DoubleMatrix1D ret = sol.viewPart(0, originalDim); DoubleMatrix1D ineq = originalProblem.getFi(ret); maxIneqIndex = Utils.getMaxIndex(ineq.toArray()); if (Log.isLoggable(MainActivity.JOPTIMIZER_LOGTAG, Log.DEBUG)) { Log.d(MainActivity.JOPTIMIZER_LOGTAG, "ineq : " + ArrayUtils.toString(ineq.toArray())); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "max ineq pos: " + maxIneqIndex); Log.d(MainActivity.JOPTIMIZER_LOGTAG, "max ineq val: " + ineq.get(maxIneqIndex)); } //if(sol[dim-1]>0){ if (ineq.get(maxIneqIndex) >= 0) { throw new Exception("Infeasible problem"); } return ret; }
From source file:com.wordpress.tonytam.avatar.AvatarWearActivity.java
@Override protected void onResume() { super.onResume(); if (mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL)) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Successfully registered for the sensor updates"); }/*from ww w .j a va 2 s .com*/ } // TODO: if (false) { if (mSensorManager.registerListener(this, mSensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL)) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Successfully registered for the sensor updates"); } } } }