_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q166200 | RideRequestDeeplink.execute | validation | public void execute() {
final CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
customTabsHelper.openCustomTab(context, intent, uri, new CustomTabsHelper.BrowserFallback());
} | java | {
"resource": ""
} |
q166201 | LoginSampleActivity.validateConfiguration | validation | private void validateConfiguration(SessionConfiguration configuration) {
String nullError = "%s must not be null";
String sampleError = "Please update your %s in the gradle.properties of the project before " +
"using the Uber SDK Sample app. For a more secure storage location, " +
"please investigate storing in your user home gradle.properties ";
checkNotNull(configuration, String.format(nullError, "SessionConfiguration"));
checkNotNull(configuration.getClientId(), String.format(nullError, "Client ID"));
checkNotNull(configuration.getRedirectUri(), String.format(nullError, "Redirect URI"));
checkState(!configuration.getClientId().equals("insert_your_client_id_here"),
String.format(sampleError, "Client ID"));
checkState(!configuration.getRedirectUri().equals("insert_your_redirect_uri_here"),
String.format(sampleError, "Redirect URI"));
} | java | {
"resource": ""
} |
q166202 | LoginActivity.newResponseIntent | validation | public static Intent newResponseIntent(Context context, Uri responseUri) {
Intent intent = new Intent(context, LoginActivity.class);
intent.setData(responseUri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
return intent;
} | java | {
"resource": ""
} |
q166203 | ConfigurationHandlerService.editMap | validation | public boolean editMap(ConfigurationHandler configurationHandler) {
String method = configurationHandler.getMethod().toUpperCase();
if (configurationHandlerMap.containsKey(Method.valueOf(method))) {
configurationHandlerMap.put(Method.valueOf(method), configurationHandler);
return true;
}
return false;
} | java | {
"resource": ""
} |
q166204 | TaskGenerator.main | validation | public static void main(String[] args) {
if(args.length!=1) {
System.err.println("Must provide one argument - Mesos master location string");
System.exit(1);
}
int numTasks=10;
int numIters=5;
BlockingQueue<TaskRequest> taskQueue = new LinkedBlockingQueue<>();
final TaskGenerator taskGenerator = new TaskGenerator(taskQueue, numIters, numTasks);
final SampleFramework framework = new SampleFramework(taskQueue, args[0], // mesos master location string
new Action1<String>() {
@Override
public void call(String s) {
taskGenerator.tasksCompleted.incrementAndGet();
}
},
new Func1<String, String>() {
@Override
public String call(String s) {
return "sleep 2";
}
});
long start = System.currentTimeMillis();
(new Thread(taskGenerator)).start();
new Thread(new Runnable() {
@Override
public void run() {
framework.runAll();
}
}).start();
while(taskGenerator.tasksCompleted.get() < (numIters*numTasks)) {
System.out.println("NUM TASKS COMPLETED: " + taskGenerator.tasksCompleted.get() + " of " + (numIters*numTasks));
try{Thread.sleep(1000);}catch(InterruptedException ie){}
}
System.out.println("Took " + (System.currentTimeMillis()-start) + " mS to complete " + (numIters*numTasks) + " tasks");
framework.shutdown();
System.exit(0);
} | java | {
"resource": ""
} |
q166205 | SampleFramework.shutdown | validation | public void shutdown() {
System.out.println("Stopping down mesos driver");
Protos.Status status = mesosSchedulerDriver.stop();
isShutdown.set(true);
} | java | {
"resource": ""
} |
q166206 | ExclusiveHostConstraint.evaluate | validation | @Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Collection<TaskRequest> runningTasks = targetVM.getRunningTasks();
if(runningTasks!=null && !runningTasks.isEmpty())
return new Result(false, "Already has " + runningTasks.size() + " tasks running on it");
Collection<TaskAssignmentResult> tasksCurrentlyAssigned = targetVM.getTasksCurrentlyAssigned();
if(tasksCurrentlyAssigned!=null && !tasksCurrentlyAssigned.isEmpty())
return new Result(false, "Already has " + tasksCurrentlyAssigned.size() + " assigned on it");
return new Result(true, "");
} | java | {
"resource": ""
} |
q166207 | HostAttrValueConstraint.evaluate | validation | @Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
String targetHostAttrVal = getAttrValue(targetVM.getCurrAvailableResources());
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
}
String requiredAttrVal = hostAttributeValueGetter.call(taskRequest.getId());
return targetHostAttrVal.equals(requiredAttrVal)?
new Result(true, "") :
new Result(false, "Host attribute " + hostAttributeName + ": required=" + requiredAttrVal + ", got=" + targetHostAttrVal);
} | java | {
"resource": ""
} |
q166208 | UniqueHostAttrConstraint.evaluate | validation | @Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Set<String> coTasks = coTasksGetter.call(taskRequest.getId());
String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName);
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
}
for(String coTask: coTasks) {
TaskTracker.ActiveTask activeTask = taskTrackerState.getAllRunningTasks().get(coTask);
if(activeTask==null)
activeTask = taskTrackerState.getAllCurrentlyAssignedTasks().get(coTask);
if(activeTask!=null) {
String usedAttrVal = AttributeUtilities.getAttrValue(activeTask.getTotalLease(), hostAttributeName);
if(usedAttrVal==null || usedAttrVal.isEmpty())
return new Result(false, hostAttributeName+" attribute unavailable on host " + activeTask.getTotalLease().hostname() +
" running co-task " + coTask);
if(usedAttrVal.equals(targetHostAttrVal)) {
return new Result(false, hostAttributeName+" " + targetHostAttrVal + " already used for another co-task " + coTask);
}
}
}
return new Result(true, "");
} | java | {
"resource": ""
} |
q166209 | TaskScheduler.setAutoscalerCallback | validation | public void setAutoscalerCallback(Action1<AutoScaleAction> callback) throws IllegalStateException {
checkIfShutdown();
if (autoScaler == null) {
throw new IllegalStateException("No autoScaler setup");
}
autoScaler.setCallback(callback);
} | java | {
"resource": ""
} |
q166210 | TaskScheduler.disableVM | validation | public void disableVM(String hostname, long durationMillis) throws IllegalStateException {
logger.debug("Disable VM " + hostname + " for " + durationMillis + " millis");
assignableVMs.disableUntil(hostname, System.currentTimeMillis() + durationMillis);
} | java | {
"resource": ""
} |
q166211 | TaskScheduler.disableVMByVMId | validation | public boolean disableVMByVMId(String vmID, long durationMillis) throws IllegalStateException {
final String hostname = assignableVMs.getHostnameFromVMId(vmID);
if (hostname == null) {
return false;
}
disableVM(hostname, durationMillis);
return true;
} | java | {
"resource": ""
} |
q166212 | TaskScheduler.enableVM | validation | public void enableVM(String hostname) throws IllegalStateException {
logger.debug("Enabling VM " + hostname);
assignableVMs.enableVM(hostname);
} | java | {
"resource": ""
} |
q166213 | TaskScheduler.shutdown | validation | public void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
executorService.shutdown();
if (autoScaler != null) {
autoScaler.shutdown();
}
}
} | java | {
"resource": ""
} |
q166214 | Entity.hasProperties | validation | public boolean hasProperties(String... properties) {
for (String property : properties) {
if (!hasProperty(property)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q166215 | Clarity.infoForSource | validation | public static Demo.CDemoFileInfo infoForSource(final Source source) throws IOException {
EngineType engineType = source.readEngineType();
source.setPosition(source.readFixedInt32());
PacketInstance<GeneratedMessage> pi = engineType.getNextPacketInstance(source);
return (Demo.CDemoFileInfo) pi.parse();
} | java | {
"resource": ""
} |
q166216 | Clarity.metadataForStream | validation | private static S2DotaMatchMetadata.CDOTAMatchMetadataFile metadataForStream(InputStream stream) throws IOException {
return Packet.parse(S2DotaMatchMetadata.CDOTAMatchMetadataFile.class, ByteString.readFrom(stream));
} | java | {
"resource": ""
} |
q166217 | CsGoEngineType.readPacket | validation | private byte[] readPacket(Source source) throws IOException {
int size = source.readFixedInt32();
return packetReader.readFromSource(source, size, false);
} | java | {
"resource": ""
} |
q166218 | Source.readVarInt32 | validation | public int readVarInt32() throws IOException {
byte tmp = readByte();
if (tmp >= 0) {
return tmp;
}
int result = tmp & 0x7f;
if ((tmp = readByte()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = readByte()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = readByte()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = readByte()) << 28;
if (tmp < 0) {
throw new IOException("malformed varint detected");
}
}
}
}
return result;
} | java | {
"resource": ""
} |
q166219 | Source.readFixedInt32 | validation | public int readFixedInt32() throws IOException {
return ByteBuffer.wrap(readBytes(4)).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();
} | java | {
"resource": ""
} |
q166220 | Source.readEngineType | validation | public EngineType readEngineType() throws IOException {
try {
engineType = EngineId.typeForMagic(new String(readBytes(8)));
if (engineType == null) {
throw new IOException();
}
return engineType;
} catch (IOException e) {
throw new IOException("given stream does not seem to contain a valid replay");
}
} | java | {
"resource": ""
} |
q166221 | ContainerTag.with | validation | public ContainerTag with(DomContent child) {
if (this == child) {
throw new RuntimeException("Cannot append a tag to itself.");
}
if (child == null) {
return this; // in some cases, like when using iff(), we ignore null children
}
children.add(child);
return this;
} | java | {
"resource": ""
} |
q166222 | ContainerTag.with | validation | public ContainerTag with(Iterable<? extends DomContent> children) {
if (children != null) {
for (DomContent child : children) {
this.with(child);
}
}
return this;
} | java | {
"resource": ""
} |
q166223 | TagCreator.iff | validation | @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <T, U> T iff(Optional<U> optional, Function<U, T> ifFunction) {
if (Objects.nonNull(optional) && optional.isPresent()) {
return optional.map(ifFunction).orElse(null);
}
return null;
} | java | {
"resource": ""
} |
q166224 | TagCreator.document | validation | public static String document(ContainerTag htmlTag) {
if (htmlTag.getTagName().equals("html")) {
return document().render() + htmlTag.render();
}
throw new IllegalArgumentException("Only HTML-tag can follow document declaration");
} | java | {
"resource": ""
} |
q166225 | Tag.setAttribute | validation | boolean setAttribute(String name, String value) {
if (value == null) {
return attributes.add(new Attribute(name));
}
for (Attribute attribute : attributes) {
if (attribute.getName().equals(name)) {
attribute.setValue(value); // update with new value
return true;
}
}
return attributes.add(new Attribute(name, value));
} | java | {
"resource": ""
} |
q166226 | Tag.attr | validation | public T attr(String attribute, Object value) {
setAttribute(attribute, value == null ? null : String.valueOf(value));
return (T) this;
} | java | {
"resource": ""
} |
q166227 | Tag.attr | validation | public T attr(Attribute attribute) {
Iterator<Attribute> iterator = attributes.iterator();
String name = attribute.getName();
if (name != null) {
// name == null is allowed, but those Attributes are not rendered. So we add them anyway.
while (iterator.hasNext()) {
Attribute existingAttribute = iterator.next();
if (existingAttribute.getName().equals(name)) {
iterator.remove();
}
}
}
attributes.add(attribute);
return (T) this;
} | java | {
"resource": ""
} |
q166228 | Tag.withClasses | validation | public T withClasses(String... classes) {
StringBuilder sb = new StringBuilder();
for (String s : classes) {
sb.append(s != null ? s : "").append(" ");
}
return attr(Attr.CLASS, sb.toString().trim());
} | java | {
"resource": ""
} |
q166229 | JSMin.compressJs | validation | public static String compressJs(String code) {
InputStream inStream = new ByteArrayInputStream(code.getBytes());
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
JSMin jsmin = new JSMin(inStream, outStream);
try {
jsmin.jsmin();
return outStream.toString().trim();
} catch (Exception e) {
e.printStackTrace();
return "";
}
} | java | {
"resource": ""
} |
q166230 | Selector.parseProperties | validation | private ArrayList<Property> parseProperties(String contents) {
ArrayList<String> parts = new ArrayList<>();
boolean bInsideString = false,
bInsideURL = false;
int j = 0;
String substr;
for (int i = 0; i < contents.length(); i++) {
if (bInsideString) { // If we're inside a string
bInsideString = !(contents.charAt(i) == '"');
} else if (bInsideURL) { // If we're inside a URL
bInsideURL = !(contents.charAt(i) == ')');
} else if (contents.charAt(i) == '"') {
bInsideString = true;
} else if (contents.charAt(i) == '(') {
if ((i - 3) > 0 && "url".equals(contents.substring(i - 3, i))) {
bInsideURL = true;
}
} else if (contents.charAt(i) == ';') {
substr = contents.substring(j, i);
if (!(substr.trim().equals(""))) {
parts.add(substr);
}
j = i + 1;
}
}
substr = contents.substring(j, contents.length());
if (!(substr.trim().equals(""))) {
parts.add(substr);
}
ArrayList<Property> results = new ArrayList<>();
for (String part : parts) {
try {
results.add(new Property(part));
} catch (IncompletePropertyException ipex) {
LOG.warning("Incomplete property in selector \"" + this.selector + "\": \"" + ipex.getMessage() + "\"");
}
}
return results;
} | java | {
"resource": ""
} |
q166231 | Property.parseValues | validation | private Part[] parseValues(String contents) {
String[] parts = contents.split(",");
Part[] results = new Part[parts.length];
for (int i = 0; i < parts.length; i++) {
try {
results[i] = new Part(parts[i], property);
} catch (Exception e) {
LOG.warning(e.getMessage());
results[i] = null;
}
}
return results;
} | java | {
"resource": ""
} |
q166232 | FloatingSearchView.handleOnVisibleMenuItemsWidthChanged | validation | private void handleOnVisibleMenuItemsWidthChanged(int menuItemsWidth) {
if (menuItemsWidth == 0) {
mClearButton.setTranslationX(-Util.dpToPx(4));
int paddingRight = Util.dpToPx(4);
if (mIsFocused) {
paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP);
} else {
paddingRight += Util.dpToPx(14);
}
mSearchInput.setPadding(0, 0, paddingRight, 0);
} else {
mClearButton.setTranslationX(-menuItemsWidth);
int paddingRight = menuItemsWidth;
if (mIsFocused) {
paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP);
}
mSearchInput.setPadding(0, 0, paddingRight, 0);
}
} | java | {
"resource": ""
} |
q166233 | FloatingSearchView.setLeftActionIconColor | validation | public void setLeftActionIconColor(int color) {
mLeftActionIconColor = color;
mMenuBtnDrawable.setColor(color);
DrawableCompat.setTint(mIconBackArrow, color);
DrawableCompat.setTint(mIconSearch, color);
} | java | {
"resource": ""
} |
q166234 | FloatingSearchView.setBackgroundColor | validation | public void setBackgroundColor(int color) {
mBackgroundColor = color;
if (mQuerySection != null && mSuggestionsList != null) {
mQuerySection.setCardBackgroundColor(color);
mSuggestionsList.setBackgroundColor(color);
}
} | java | {
"resource": ""
} |
q166235 | FloatingSearchView.openMenu | validation | public void openMenu(boolean withAnim) {
mMenuOpen = true;
openMenuDrawable(mMenuBtnDrawable, withAnim);
if (mOnMenuClickListener != null) {
mOnMenuClickListener.onMenuOpened();
}
} | java | {
"resource": ""
} |
q166236 | FloatingSearchView.closeMenu | validation | public void closeMenu(boolean withAnim) {
mMenuOpen = false;
closeMenuDrawable(mMenuBtnDrawable, withAnim);
if (mOnMenuClickListener != null) {
mOnMenuClickListener.onMenuClosed();
}
} | java | {
"resource": ""
} |
q166237 | FloatingSearchView.inflateOverflowMenu | validation | public void inflateOverflowMenu(int menuId) {
mMenuId = menuId;
mMenuView.reset(menuId, actionMenuAvailWidth());
if (mIsFocused) {
mMenuView.hideIfRoomItems(false);
}
} | java | {
"resource": ""
} |
q166238 | FloatingSearchView.setShowSearchKey | validation | public void setShowSearchKey(boolean show) {
mShowSearchKey = show;
if (show) {
mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
} else {
mSearchInput.setImeOptions(EditorInfo.IME_ACTION_NONE);
}
} | java | {
"resource": ""
} |
q166239 | FloatingSearchView.setDismissOnOutsideClick | validation | public void setDismissOnOutsideClick(boolean enable) {
mDismissOnOutsideTouch = enable;
mSuggestionsSection.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//todo check if this is called twice
if (mDismissOnOutsideTouch && mIsFocused) {
setSearchFocusedInternal(false);
}
return true;
}
});
} | java | {
"resource": ""
} |
q166240 | FloatingSearchView.setSearchFocused | validation | public boolean setSearchFocused(final boolean focused) {
boolean updatedToNotFocused = !focused && this.mIsFocused;
if ((focused != this.mIsFocused) && mSuggestionSecHeightListener == null) {
if (mIsSuggestionsSectionHeightSet) {
setSearchFocusedInternal(focused);
} else {
mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() {
@Override
public void onSuggestionSecHeightSet() {
setSearchFocusedInternal(focused);
mSuggestionSecHeightListener = null;
}
};
}
}
return updatedToNotFocused;
} | java | {
"resource": ""
} |
q166241 | FloatingSearchView.updateSuggestionsSectionHeight | validation | private boolean updateSuggestionsSectionHeight(List<? extends SearchSuggestion>
newSearchSuggestions, boolean withAnim) {
final int cardTopBottomShadowPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT);
final int cardRadiusSize = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT);
int visibleSuggestionHeight = calculateSuggestionItemsHeight(newSearchSuggestions,
mSuggestionListContainer.getHeight());
int diff = mSuggestionListContainer.getHeight() - visibleSuggestionHeight;
int addedTranslationYForShadowOffsets = (diff <= cardTopBottomShadowPadding) ?
-(cardTopBottomShadowPadding - diff) :
diff < (mSuggestionListContainer.getHeight() - cardTopBottomShadowPadding) ? cardRadiusSize : 0;
final float newTranslationY = -mSuggestionListContainer.getHeight() +
visibleSuggestionHeight + addedTranslationYForShadowOffsets;
//todo go over
final float fullyInvisibleTranslationY = -mSuggestionListContainer.getHeight() + cardRadiusSize;
ViewCompat.animate(mSuggestionListContainer).cancel();
if (withAnim) {
ViewCompat.animate(mSuggestionListContainer).
setInterpolator(SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR).
setDuration(mSuggestionSectionAnimDuration).
translationY(newTranslationY)
.setUpdateListener(new ViewPropertyAnimatorUpdateListener() {
@Override
public void onAnimationUpdate(View view) {
if (mOnSuggestionsListHeightChanged != null) {
float newSuggestionsHeight = Math.abs(view.getTranslationY() - fullyInvisibleTranslationY);
mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight);
}
}
})
.setListener(new ViewPropertyAnimatorListenerAdapter() {
@Override
public void onAnimationCancel(View view) {
mSuggestionListContainer.setTranslationY(newTranslationY);
}
}).start();
} else {
mSuggestionListContainer.setTranslationY(newTranslationY);
if (mOnSuggestionsListHeightChanged != null) {
float newSuggestionsHeight = Math.abs(mSuggestionListContainer.getTranslationY() - fullyInvisibleTranslationY);
mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight);
}
}
return mSuggestionListContainer.getHeight() == visibleSuggestionHeight;
} | java | {
"resource": ""
} |
q166242 | FloatingSearchView.calculateSuggestionItemsHeight | validation | private int calculateSuggestionItemsHeight(List<? extends SearchSuggestion> suggestions, int max) {
//todo
// 'i < suggestions.size()' in the below 'for' seems unneeded, investigate if there is a use for it.
int visibleItemsHeight = 0;
for (int i = 0; i < suggestions.size() && i < mSuggestionsList.getChildCount(); i++) {
visibleItemsHeight += mSuggestionsList.getChildAt(i).getHeight();
if (visibleItemsHeight > max) {
visibleItemsHeight = max;
break;
}
}
return visibleItemsHeight;
} | java | {
"resource": ""
} |
q166243 | FloatingSearchView.setOnBindSuggestionCallback | validation | public void setOnBindSuggestionCallback(SearchSuggestionsAdapter.OnBindSuggestionCallback callback) {
this.mOnBindSuggestionCallback = callback;
if (mSuggestionsAdapter != null) {
mSuggestionsAdapter.setOnBindSuggestionCallback(mOnBindSuggestionCallback);
}
} | java | {
"resource": ""
} |
q166244 | MD5Checksum.getMD5Checksum | validation | public static String getMD5Checksum(String filename) {
try {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
} catch (Exception e){
return "";
}
} | java | {
"resource": ""
} |
q166245 | OkHttpUtils.configureToIgnoreCertificate | validation | public static OkHttpClient.Builder configureToIgnoreCertificate(OkHttpClient.Builder builder) {
log.warn("Ignore Ssl Certificate");
try {
/*Create a trust manager that does not validate certificate chains*/
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
/*Install the all-trusting trust manager*/
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
/*Create an ssl socket factory with our all-trusting manager*/
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
log.warn("Exception while configuring IgnoreSslCertificate" + e, e);
}
return builder;
} | java | {
"resource": ""
} |
q166246 | ExpectedSubtypesAdapter.read | validation | @SuppressWarnings("unchecked")
@Override
public T read(JsonReader in) throws IOException {
List<Exception> exceptions = new ArrayList<>(subtypes.length);
ReaderSupplier readerSupplier = readForSupplier(in);
for (TypeAdapter<?> typeAdapter : adapters) {
try {
return (T) typeAdapter.read(readerSupplier.create());
} catch (Exception ex) {
exceptions.add(ex);
}
}
JsonParseException failure = new JsonParseException(
String.format(
"Cannot parse %s with following subtypes: %s",
type,
Arrays.toString(subtypes)));
for (Exception exception : exceptions) {
failure.addSuppressed(exception);
}
throw failure;
} | java | {
"resource": ""
} |
q166247 | Constitution.typeAbstract | validation | @Value.Lazy
public NameForms typeAbstract() {
if (protoclass().kind().isConstructor()) {
return typeValue();
}
List<String> classSegments = Lists.newArrayListWithExpectedSize(2);
Element e = SourceNames.collectClassSegments(protoclass().sourceElement(), classSegments);
verify(e instanceof PackageElement);
String packageOf = ((PackageElement) e).getQualifiedName().toString();
String relative = DOT_JOINER.join(classSegments);
boolean relativeAlreadyQualified = false;
if (!implementationPackage().equals(packageOf)) {
relative = DOT_JOINER.join(packageOf, relative);
relativeAlreadyQualified = true;
}
return ImmutableConstitution.NameForms.builder()
.simple(names().typeAbstract)
.relativeRaw(relative)
.packageOf(packageOf)
.genericArgs(generics().args())
.relativeAlreadyQualified(relativeAlreadyQualified)
.visibility(protoclass().visibility())
.build();
} | java | {
"resource": ""
} |
q166248 | Constitution.inPackage | validation | private String inPackage(String topLevel, String... nested) {
return DOT_JOINER.join(null, topLevel, (Object[]) nested);
} | java | {
"resource": ""
} |
q166249 | Constitution.typeImmutable | validation | @Value.Lazy
public NameForms typeImmutable() {
String simple, relative;
if (protoclass().kind().isNested()) {
String enclosingSimpleName = typeImmutableEnclosingSimpleName();
simple = names().typeImmutableNested();
relative = inPackage(enclosingSimpleName, simple);
} else if (hasImmutableInBuilder()) {
simple = names().typeImmutable;
relative = inPackage(typeBuilderSimpleName(), simple);
} else {
simple = names().typeImmutable;
relative = inPackage(simple);
}
return ImmutableConstitution.NameForms.builder()
.simple(simple)
.relativeRaw(relative)
.genericArgs(generics().args())
.packageOf(implementationPackage())
.visibility(implementationVisibility())
.build();
} | java | {
"resource": ""
} |
q166250 | TypeAdapters.create | validation | @SuppressWarnings("unchecked")
@Override
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (ID_TYPE_TOKEN.equals(type)) {
return (TypeAdapter<T>) WRAPPED_ID_ADAPTER;
}
if (TIME_INSTANT_TYPE_TOKEN.equals(type)) {
return (TypeAdapter<T>) WRAPPED_TIME_INSTANT_ADAPTER;
}
if (BINARY_TYPE_TOKEN.equals(type)) {
return (TypeAdapter<T>) WRAPPED_BINARY_ADAPTER;
}
if (PATTERN_TYPE_TOKEN.equals(type)) {
return (TypeAdapter<T>) PATTERN_ADAPTER;
}
if (DECIMAL128_TYPE_TOKEN.equals(type)) {
return (TypeAdapter<T>) DECIMAL128_ADAPTER;
}
return null;
} | java | {
"resource": ""
} |
q166251 | ImmutableOrdinalSet.of | validation | @SuppressWarnings("unchecked")
public static <E extends OrdinalValue<E>> ImmutableOrdinalSet<E> of() {
// safe unchecked: will contain no elements
return (ImmutableOrdinalSet<E>) EMPTY_SET;
} | java | {
"resource": ""
} |
q166252 | OrdinalDomain.iterator | validation | @Override
public Iterator<E> iterator() {
return new AbstractIterator<E>() {
private final int length = length();
private int index = 0;
@Override
protected E computeNext() {
int p = index++;
if (p < length) {
return get(p);
}
return endOfData();
}
};
} | java | {
"resource": ""
} |
q166253 | AttributeBuilderReflection.cachingKey | validation | private static String cachingKey(ValueAttribute valueAttribute) {
return String.format("%s-%s",
valueAttribute.containedTypeElement.getQualifiedName(),
Joiner.on(".").join(valueAttribute.containingType.constitution.style().attributeBuilder()));
} | java | {
"resource": ""
} |
q166254 | ValueAttribute.getSerializedName | validation | public String getSerializedName() {
if (serializedName == null) {
Optional<SerializedNameMirror> serializedNameAnnotation = SerializedNameMirror.find(element);
if (serializedNameAnnotation.isPresent()) {
SerializedNameMirror m = serializedNameAnnotation.get();
serializedName = m.value();
alternateSerializedNames = m.alternate();
return serializedName;
}
Optional<NamedMirror> namedAnnotation = NamedMirror.find(element);
if (namedAnnotation.isPresent()) {
String value = namedAnnotation.get().value();
if (!value.isEmpty()) {
serializedName = value;
return serializedName;
}
}
Optional<OkNamedMirror> okNamedAnnotation = OkNamedMirror.find(element);
if (okNamedAnnotation.isPresent()) {
String value = okNamedAnnotation.get().name();
if (!value.isEmpty()) {
serializedName = value;
return serializedName;
}
}
if (isMarkedAsMongoId()) {
serializedName = ID_ATTRIBUTE_NAME;
return serializedName;
}
serializedName = "";
return serializedName;
}
return serializedName;
} | java | {
"resource": ""
} |
q166255 | ValueAttribute.getMarshaledName | validation | public String getMarshaledName() {
String serializedName = getSerializedName();
if (!serializedName.isEmpty()) {
return serializedName;
}
return names.raw;
} | java | {
"resource": ""
} |
q166256 | InMemoryExpressionEvaluator.of | validation | public static <T> Predicate<T> of(Expression<T> expression) {
if (Expressions.isNil(expression)) {
// always true
return instance -> true;
}
return new InMemoryExpressionEvaluator<>(expression);
} | java | {
"resource": ""
} |
q166257 | FluentFutures.from | validation | public static <V> FluentFuture<V> from(ListenableFuture<V> future) {
if (future instanceof FluentFuture<?>) {
return (FluentFuture<V>) future;
}
return new WrapingFluentFuture<>(future, MoreExecutors.directExecutor());
} | java | {
"resource": ""
} |
q166258 | OptionalMap.getImmutable | validation | @Encoding.Expose
public Optional<ImmutableMap<K, V>> getImmutable() {
return Optional.ofNullable(map);
} | java | {
"resource": ""
} |
q166259 | TypeHierarchyCollector.stringify | validation | protected String stringify(DeclaredType input, TypevarContext context) {
return toTypeElement(input).getQualifiedName().toString();
} | java | {
"resource": ""
} |
q166260 | JsonParserReader.nextTokenBuffer | validation | public final TokenBuffer nextTokenBuffer() throws IOException {
TokenBuffer buffer = new TokenBuffer(parser);
// if token is consumed, but undelying parser is still sitting on this token, we move forward
requirePeek();
buffer.copyCurrentStructure(parser);
// when we will return to reading from reader, state will be cleared and nextToken after
clearPeek();
return buffer;
} | java | {
"resource": ""
} |
q166261 | HtmlUnitAlert.close | validation | void close() {
lock.lock();
condition.signal();
setAutoAccept(true);
lock.unlock();
holder_ = null;
} | java | {
"resource": ""
} |
q166262 | AsyncScriptExecutor.execute | validation | public Object execute(String scriptBody, Object[] parameters) {
try {
asyncResult = new AsyncScriptResult();
Function function = createInjectedScriptFunction(scriptBody, asyncResult);
try {
page.executeJavaScriptFunction(function, function, parameters,
page.getDocumentElement());
} catch (ScriptException e) {
throw new WebDriverException(e);
}
try {
return asyncResult.waitForResult(timeoutMillis);
} catch (InterruptedException e) {
throw new WebDriverException(e);
}
}
finally {
asyncResult = null;
}
} | java | {
"resource": ""
} |
q166263 | HtmlUnitDriver.setProxySettings | validation | public void setProxySettings(Proxy proxy) {
if (proxy == null || proxy.getProxyType() == Proxy.ProxyType.UNSPECIFIED) {
return;
}
switch (proxy.getProxyType()) {
case MANUAL:
List<String> noProxyHosts = new ArrayList<>();
String noProxy = proxy.getNoProxy();
if (noProxy != null && !noProxy.isEmpty()) {
String[] hosts = noProxy.split(",");
for (String host : hosts) {
if (host.trim().length() > 0) {
noProxyHosts.add(host.trim());
}
}
}
String httpProxy = proxy.getHttpProxy();
if (httpProxy != null && !httpProxy.isEmpty()) {
String host = httpProxy;
int port = 0;
int index = httpProxy.indexOf(":");
if (index != -1) {
host = httpProxy.substring(0, index);
port = Integer.parseInt(httpProxy.substring(index + 1));
}
setHTTPProxy(host, port, noProxyHosts);
}
String socksProxy = proxy.getSocksProxy();
if (socksProxy != null && !socksProxy.isEmpty()) {
String host = socksProxy;
int port = 0;
int index = socksProxy.indexOf(":");
if (index != -1) {
host = socksProxy.substring(0, index);
port = Integer.parseInt(socksProxy.substring(index + 1));
}
setSocksProxy(host, port, noProxyHosts);
}
// sslProxy is not supported/implemented
// ftpProxy is not supported/implemented
break;
case PAC:
String pac = proxy.getProxyAutoconfigUrl();
if (pac != null && !pac.isEmpty()) {
setAutoProxy(pac);
}
break;
default:
break;
}
} | java | {
"resource": ""
} |
q166264 | HtmlUnitDriver.setHTTPProxy | validation | public void setHTTPProxy(String host, int port, List<String> noProxyHosts) {
proxyConfig = new ProxyConfig();
proxyConfig.setProxyHost(host);
proxyConfig.setProxyPort(port);
if (noProxyHosts != null && noProxyHosts.size() > 0) {
for (String noProxyHost : noProxyHosts) {
proxyConfig.addHostsToProxyBypass(noProxyHost);
}
}
getWebClient().getOptions().setProxyConfig(proxyConfig);
} | java | {
"resource": ""
} |
q166265 | HtmlUnitDriver.setAutoProxy | validation | public void setAutoProxy(String autoProxyUrl) {
proxyConfig = new ProxyConfig();
proxyConfig.setProxyAutoConfigUrl(autoProxyUrl);
getWebClient().getOptions().setProxyConfig(proxyConfig);
} | java | {
"resource": ""
} |
q166266 | BoxHelper.userClient | validation | public static BoxDeveloperEditionAPIConnection userClient(String userId) {
if (userId == null) { // session data has expired
return null;
}
System.out.format("userClient called with userId %s \n\n", userId);
try {
BoxDeveloperEditionAPIConnection userClient = BoxDeveloperEditionAPIConnection.getAppUserConnection(
userId, CLIENT_ID, CLIENT_SECRET, jwtEncryptionPreferences, accessTokenCache);
return userClient;
} catch (BoxAPIException apiException) {
apiException.printStackTrace();
throw apiException;
}
} | java | {
"resource": ""
} |
q166267 | ProcessDefinitionEntity.updateModifiedFieldsFromEntity | validation | public void updateModifiedFieldsFromEntity(ProcessDefinitionEntity updatingProcessDefinition) {
if (!this.key.equals(updatingProcessDefinition.key) || !this.deploymentId.equals(updatingProcessDefinition.deploymentId)) {
throw new ProcessEngineException("Cannot update entity from an unrelated process definition");
}
// TODO: add a guard once the mismatch between revisions in deployment cache and database has been resolved
this.revision = updatingProcessDefinition.revision;
this.suspensionState = updatingProcessDefinition.suspensionState;
} | java | {
"resource": ""
} |
q166268 | FourEyesExtensionsParseListener.addFourEyesTaskListener | validation | private void addFourEyesTaskListener(ActivityImpl activity) {
UserTaskActivityBehavior userTaskActivityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
boolean listenerAlreadyExists = false;
// check that the listener wasn't added in the XML explicitly
List<TaskListener> existingListeners = userTaskActivityBehavior.getTaskDefinition().getTaskListeners().get("complete");
for (TaskListener taskListener : existingListeners) {
if (taskListener instanceof ClassDelegate &&
((ClassDelegate)taskListener).getClassName().equals(TaskCompletionListener.class.getName())) {
listenerAlreadyExists = true;
logger.info(TaskCompletionListener.class.getSimpleName() + " was already explicitly added to usertask in the bpmn xml.");
break;
}
}
if (!listenerAlreadyExists) {
logger.info("Adding " + TaskCompletionListener.class.getSimpleName() + " implicitly to usertask.");
ClassDelegate taskListener = new ClassDelegate(TaskCompletionListener.class, null);
userTaskActivityBehavior.getTaskDefinition().addTaskListener("complete", taskListener);
}
} | java | {
"resource": ""
} |
q166269 | ExampleTenantAwareProcessApplication.deployProcessesToTenantEngines | validation | @PostDeploy
public void deployProcessesToTenantEngines() {
// copy the process definitions deployed to the default engine to all tenants
for (ProcessEngine processEngine : BpmPlatform.getProcessEngineService().getProcessEngines()) {
if (processEngine != BpmPlatform.getDefaultProcessEngine()) {
TenantManager.deployDefaultProcessesToEngine(processEngine);
}
}
} | java | {
"resource": ""
} |
q166270 | PortalContextAssociationManager.checkTaskSelectedViaBridge | validation | private void checkTaskSelectedViaBridge() {
String bridgeTaskId = (String) getSharedSessionAttribute(BRIDGE_TASK_ID);
String selectedTaskId = (String) getSharedSessionAttribute(ASSOCIATED_TASK_ID);
if (selectedTaskId == null && bridgeTaskId != null) {
switchTaskId(bridgeTaskId);
}
if (selectedTaskId != null && bridgeTaskId != null && !selectedTaskId.equals(bridgeTaskId)) {
// task switched, TODO: think about if correct like this
switchTaskId(bridgeTaskId);
}
} | java | {
"resource": ""
} |
q166271 | ProcessApplicationHelper.getServletContextPath | validation | public static String getServletContextPath(
ProcessEngine processEngine, String processDefinitionId) {
return getServletContextPath(getProcessApplicationInfo(processEngine, processDefinitionId));
} | java | {
"resource": ""
} |
q166272 | ProcessApplicationHelper.getServletContextPath | validation | public static String getServletContextPath(String processDefinitionId) {
ProcessApplicationInfo processApplicationInfo = getProcessApplicationInfo(processDefinitionId);
if (processApplicationInfo == null) {
return null;
}
return processApplicationInfo.getProperties().get(
ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH);
} | java | {
"resource": ""
} |
q166273 | ProcessApplicationHelper.getProcessApplicationInfo | validation | public static ProcessApplicationInfo getProcessApplicationInfo(
ProcessEngine processEngine, String processDefinitionId) {
ProcessDefinition processDefinition = processEngine.getRepositoryService().getProcessDefinition(processDefinitionId);
// get the name of the process application that made the deployment
String processApplicationName = processEngine.getManagementService()
.getProcessApplicationForDeployment(processDefinition.getDeploymentId());
if (processApplicationName == null) {
// not a process application deployment
return null;
} else {
ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService();
return processApplicationService.getProcessApplicationInfo(processApplicationName);
}
} | java | {
"resource": ""
} |
q166274 | ProcessApplicationHelper.getProcessApplicationInfo | validation | public static ProcessApplicationInfo getProcessApplicationInfo(String processDefinitionId) {
ProcessEngineService processEngineService = BpmPlatform.getProcessEngineService();
ProcessApplicationService processAppService = BpmPlatform.getProcessApplicationService();
// iterate over all process applications
for (String appName : processAppService.getProcessApplicationNames()) {
ProcessApplicationInfo appInfo = processAppService
.getProcessApplicationInfo(appName);
// iterate over all deployments of a process application
for (ProcessApplicationDeploymentInfo deploymentInfo : appInfo
.getDeploymentInfo()) {
long count = processEngineService
.getProcessEngine(deploymentInfo.getProcessEngineName())
.getRepositoryService().createProcessDefinitionQuery()
.deploymentId(deploymentInfo.getDeploymentId())
.processDefinitionId(processDefinitionId).count();
if (count > 0) {
return appInfo;
}
}
}
return null;
} | java | {
"resource": ""
} |
q166275 | SecurityConfig.userDetailsService | validation | @SuppressWarnings("deprecation")
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withDefaultPasswordEncoder().username("demo").password("demo").roles("ACTUATOR", "camunda-admin").build());
manager.createUser(User.withDefaultPasswordEncoder().username("john").password("john").roles("camunda-user").build());
return manager;
} | java | {
"resource": ""
} |
q166276 | AbstractProcessVariableAdapter.castValue | validation | @SuppressWarnings("unchecked")
public static final <T extends Serializable> T castValue(final Object value) {
return value != null ? (T) value : null;
} | java | {
"resource": ""
} |
q166277 | CamelBootStrap.init | validation | @PostConstruct
public void init() throws Exception {
log.info("=======================");
log.info("Adding camunda BPM Component to Camel");
log.info("=======================");
CamundaBpmComponent component = new CamundaBpmComponent(processEngine);
component.setCamelContext(cdiCamelContext);
cdiCamelContext.addComponent("camunda-bpm", component); // TODO: could be done by META-INF/service as well- maybe switch?
// For simplicity JMS was removed from the example - but you can easily re-add it:
// inject the JMS connection factory into camel's JMS component
// JmsComponent jmsComponent = cdiCamelContext.getComponent("jms", JmsComponent.class);
// jmsComponent.setConnectionFactory(queueConnectionFactory);
// Instead we exchanged the JMS component by replacing it with Camel seda component for in memory queues
cdiCamelContext.addComponent("jms", cdiCamelContext.getComponent("seda", SedaComponent.class));
// add routes to camel context
log.info("=======================");
log.info("adding OpenAccountRoute to camel context");
log.info("=======================");
cdiCamelContext.addRoutes(openAccountRoute);
log.info("=======================");
log.info("Camel Components: " + cdiCamelContext.getComponentNames());
log.info("=======================");
log.info("=======================");
log.info("starting camel context");
log.info("=======================");
// cdiCamelContext.setTracing(true);
cdiCamelContext.start();
log.info("=======================");
log.info("successfully created camel context and started open account route!");
log.info("=======================");
} | java | {
"resource": ""
} |
q166278 | Guards.checkIsSet | validation | public static void checkIsSet(final DelegateExecution execution, final String variableName) {
checkArgument(variableName != null, VARIABLE_NAME_MUST_BE_NOT_NULL);
final Object variableLocal = execution.getVariableLocal(variableName);
final Object variable = execution.getVariable(variableName);
checkState(variableLocal != null || variable != null,
format(CONDITION_VIOLATED + "Variable '%s' is not set.", execution.getCurrentActivityId(), variableName));
} | java | {
"resource": ""
} |
q166279 | Guards.checkIsSetGlobal | validation | public static void checkIsSetGlobal(final DelegateExecution execution, final String variableName) {
checkArgument(variableName != null, VARIABLE_NAME_MUST_BE_NOT_NULL);
final Object variable = execution.getVariable(variableName);
checkState(variable != null, format(CONDITION_VIOLATED + "Global variable '%s' is not set.", execution.getCurrentActivityId(), variableName));
} | java | {
"resource": ""
} |
q166280 | FloatingActionMenu.open | validation | public void open(boolean animated) {
// Get the center of the action view from the following function for efficiency
// populate destination x,y coordinates of Items
Point center = calculateItemPositions();
WindowManager.LayoutParams overlayParams = null;
if(systemOverlay) {
// If this is a system overlay menu, use the overlay container and place it behind
// the main action button so that all the views will be added into it.
attachOverlayContainer();
overlayParams = (WindowManager.LayoutParams) overlayContainer.getLayoutParams();
}
if(animated && animationHandler != null) {
// If animations are enabled and we have a MenuAnimationHandler, let it do the heavy work
if(animationHandler.isAnimating()) {
// Do not proceed if there is an animation currently going on.
return;
}
for (int i = 0; i < subActionItems.size(); i++) {
// It is required that these Item views are not currently added to any parent
// Because they are supposed to be added to the Activity content view,
// just before the animation starts
if (subActionItems.get(i).view.getParent() != null) {
throw new RuntimeException("All of the sub action items have to be independent from a parent.");
}
// Initially, place all items right at the center of the main action view
// Because they are supposed to start animating from that point.
final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);
if(systemOverlay) {
params.setMargins(center.x - overlayParams.x - subActionItems.get(i).width / 2, center.y - overlayParams.y - subActionItems.get(i).height / 2, 0, 0);
}
else {
params.setMargins(center.x - subActionItems.get(i).width / 2, center.y - subActionItems.get(i).height / 2, 0, 0);
}
addViewToCurrentContainer(subActionItems.get(i).view, params);
}
// Tell the current MenuAnimationHandler to animate from the center
animationHandler.animateMenuOpening(center);
}
else {
// If animations are disabled, just place each of the items to their calculated destination positions.
for (int i = 0; i < subActionItems.size(); i++) {
// This is currently done by giving them large margins
final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);
if(systemOverlay) {
params.setMargins(subActionItems.get(i).x - overlayParams.x, subActionItems.get(i).y - overlayParams.y, 0, 0);
subActionItems.get(i).view.setLayoutParams(params);
}
else {
params.setMargins(subActionItems.get(i).x, subActionItems.get(i).y, 0, 0);
subActionItems.get(i).view.setLayoutParams(params);
// Because they are placed into the main content view of the Activity,
// which is itself a FrameLayout
}
addViewToCurrentContainer(subActionItems.get(i).view, params);
}
}
// do not forget to specify that the menu is open.
open = true;
if(stateChangeListener != null) {
stateChangeListener.onMenuOpened(this);
}
} | java | {
"resource": ""
} |
q166281 | FloatingActionMenu.close | validation | public void close(boolean animated) {
// If animations are enabled and we have a MenuAnimationHandler, let it do the heavy work
if(animated && animationHandler != null) {
if(animationHandler.isAnimating()) {
// Do not proceed if there is an animation currently going on.
return;
}
animationHandler.animateMenuClosing(getActionViewCenter());
}
else {
// If animations are disabled, just detach each of the Item views from the Activity content view.
for (int i = 0; i < subActionItems.size(); i++) {
removeViewFromCurrentContainer(subActionItems.get(i).view);
}
detachOverlayContainer();
}
// do not forget to specify that the menu is now closed.
open = false;
if(stateChangeListener != null) {
stateChangeListener.onMenuClosed(this);
}
} | java | {
"resource": ""
} |
q166282 | FloatingActionMenu.updateItemPositions | validation | public void updateItemPositions() {
// Only update if the menu is currently open
if(!isOpen()) {
return;
}
// recalculate x,y coordinates of Items
calculateItemPositions();
// Simply update layout params for each item
for (int i = 0; i < subActionItems.size(); i++) {
// This is currently done by giving them large margins
final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);
params.setMargins(subActionItems.get(i).x, subActionItems.get(i).y, 0, 0);
subActionItems.get(i).view.setLayoutParams(params);
}
} | java | {
"resource": ""
} |
q166283 | FloatingActionMenu.getActionViewCoordinates | validation | private Point getActionViewCoordinates() {
int[] coords = new int[2];
// This method returns a x and y values that can be larger than the dimensions of the device screen.
mainActionView.getLocationOnScreen(coords);
// So, we need to deduce the offsets.
if(systemOverlay) {
coords[1] -= getStatusBarHeight();
}
else {
Rect activityFrame = new Rect();
getActivityContentView().getWindowVisibleDisplayFrame(activityFrame);
coords[0] -= (getScreenSize().x - getActivityContentView().getMeasuredWidth());
coords[1] -= (activityFrame.height() + activityFrame.top - getActivityContentView().getMeasuredHeight());
}
return new Point(coords[0], coords[1]);
} | java | {
"resource": ""
} |
q166284 | FloatingActionMenu.getActionViewCenter | validation | public Point getActionViewCenter() {
Point point = getActionViewCoordinates();
point.x += mainActionView.getMeasuredWidth() / 2;
point.y += mainActionView.getMeasuredHeight() / 2;
return point;
} | java | {
"resource": ""
} |
q166285 | FloatingActionMenu.calculateItemPositions | validation | private Point calculateItemPositions() {
// Create an arc that starts from startAngle and ends at endAngle
// in an area that is as large as 4*radius^2
final Point center = getActionViewCenter();
RectF area = new RectF(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
Path orbit = new Path();
orbit.addArc(area, startAngle, endAngle - startAngle);
PathMeasure measure = new PathMeasure(orbit, false);
// Prevent overlapping when it is a full circle
int divisor;
if(Math.abs(endAngle - startAngle) >= 360 || subActionItems.size() <= 1) {
divisor = subActionItems.size();
}
else {
divisor = subActionItems.size() -1;
}
// Measure this path, in order to find points that have the same distance between each other
for(int i=0; i<subActionItems.size(); i++) {
float[] coords = new float[] {0f, 0f};
measure.getPosTan((i) * measure.getLength() / divisor, coords, null);
// get the x and y values of these points and set them to each of sub action items.
subActionItems.get(i).x = (int) coords[0] - subActionItems.get(i).width / 2;
subActionItems.get(i).y = (int) coords[1] - subActionItems.get(i).height / 2;
}
return center;
} | java | {
"resource": ""
} |
q166286 | FloatingActionMenu.getActivityContentView | validation | public View getActivityContentView() {
try {
return ((Activity) mainActionView.getContext()).getWindow().getDecorView().findViewById(android.R.id.content);
}
catch(ClassCastException e) {
throw new ClassCastException("Please provide an Activity context for this FloatingActionMenu.");
}
} | java | {
"resource": ""
} |
q166287 | FloatingActionMenu.getScreenSize | validation | private Point getScreenSize() {
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
return size;
} | java | {
"resource": ""
} |
q166288 | MenuAnimationHandler.restoreSubActionViewAfterAnimation | validation | protected void restoreSubActionViewAfterAnimation(FloatingActionMenu.Item subActionItem, ActionType actionType) {
ViewGroup.LayoutParams params = subActionItem.view.getLayoutParams();
subActionItem.view.setTranslationX(0);
subActionItem.view.setTranslationY(0);
subActionItem.view.setRotation(0);
subActionItem.view.setScaleX(1);
subActionItem.view.setScaleY(1);
subActionItem.view.setAlpha(1);
if(actionType == ActionType.OPENING) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params;
if(menu.isSystemOverlay()) {
WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams();
lp.setMargins(subActionItem.x - overlayParams.x, subActionItem.y - overlayParams.y, 0, 0);
}
else {
lp.setMargins(subActionItem.x, subActionItem.y, 0, 0);
}
subActionItem.view.setLayoutParams(lp);
}
else if(actionType == ActionType.CLOSING) {
Point center = menu.getActionViewCenter();
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params;
if(menu.isSystemOverlay()) {
WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams();
lp.setMargins(center.x - overlayParams.x - subActionItem.width / 2, center.y - overlayParams.y - subActionItem.height / 2, 0, 0);
}
else {
lp.setMargins(center.x - subActionItem.width / 2, center.y - subActionItem.height / 2, 0, 0);
}
subActionItem.view.setLayoutParams(lp);
menu.removeViewFromCurrentContainer(subActionItem.view);
if(menu.isSystemOverlay()) {
// When all the views are removed from the overlay container,
// we also need to detach it
if (menu.getOverlayContainer().getChildCount() == 0) {
menu.detachOverlayContainer();
}
}
}
} | java | {
"resource": ""
} |
q166289 | SubActionButton.setContentView | validation | public void setContentView(View contentView, FrameLayout.LayoutParams params) {
if(params == null) {
params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin);
params.setMargins(margin, margin, margin, margin);
}
contentView.setClickable(false);
this.addView(contentView, params);
} | java | {
"resource": ""
} |
q166290 | FloatingActionButton.setPosition | validation | public void setPosition(int position, ViewGroup.LayoutParams layoutParams) {
boolean setDefaultMargin = false;
int gravity;
switch (position) {
case POSITION_TOP_CENTER:
gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
break;
case POSITION_TOP_RIGHT:
gravity = Gravity.TOP | Gravity.RIGHT;
break;
case POSITION_RIGHT_CENTER:
gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
break;
case POSITION_BOTTOM_CENTER:
gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
break;
case POSITION_BOTTOM_LEFT:
gravity = Gravity.BOTTOM | Gravity.LEFT;
break;
case POSITION_LEFT_CENTER:
gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
break;
case POSITION_TOP_LEFT:
gravity = Gravity.TOP | Gravity.LEFT;
break;
case POSITION_BOTTOM_RIGHT:
default:
setDefaultMargin = true;
gravity = Gravity.BOTTOM | Gravity.RIGHT;
break;
}
if(!systemOverlay) {
try {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) layoutParams;
lp.gravity = gravity;
setLayoutParams(lp);
} catch (ClassCastException e) {
throw new ClassCastException("layoutParams must be an instance of " +
"FrameLayout.LayoutParams, since this FAB is not a systemOverlay");
}
}
else {
try {
WindowManager.LayoutParams lp = (WindowManager.LayoutParams) layoutParams;
lp.gravity = gravity;
if(setDefaultMargin) {
int margin = getContext().getResources().getDimensionPixelSize(R.dimen.action_button_margin);
lp.x = margin;
lp.y = margin;
}
setLayoutParams(lp);
} catch(ClassCastException e) {
throw new ClassCastException("layoutParams must be an instance of " +
"WindowManager.LayoutParams, since this FAB is a systemOverlay");
}
}
} | java | {
"resource": ""
} |
q166291 | FloatingActionButton.attach | validation | public void attach(ViewGroup.LayoutParams layoutParams) {
if(systemOverlay) {
try {
getWindowManager().addView(this, layoutParams);
}
catch(SecurityException e) {
throw new SecurityException("Your application must have SYSTEM_ALERT_WINDOW " +
"permission to create a system window.");
}
}
else {
((ViewGroup) getActivityContentView()).addView(this, layoutParams);
}
} | java | {
"resource": ""
} |
q166292 | StateConfiguration.permit | validation | public StateConfiguration<S, T> permit(T trigger, S destinationState) {
enforceNotIdentityTransition(destinationState);
return publicPermit(trigger, destinationState);
} | java | {
"resource": ""
} |
q166293 | StateConfiguration.permitIf | validation | public StateConfiguration<S, T> permitIf(T trigger, S destinationState, FuncBoolean guard) {
enforceNotIdentityTransition(destinationState);
return publicPermitIf(trigger, destinationState, guard);
} | java | {
"resource": ""
} |
q166294 | StateConfiguration.permitIfOtherwiseIgnore | validation | public StateConfiguration<S, T> permitIfOtherwiseIgnore(T trigger, S destinationState, final FuncBoolean guard) {
enforceNotIdentityTransition(destinationState);
ignoreIf(trigger, new FuncBoolean() {
@Override
public boolean call() {
return !guard.call();
}
});
return publicPermitIf(trigger, destinationState, guard);
} | java | {
"resource": ""
} |
q166295 | StateConfiguration.ignoreIf | validation | public StateConfiguration<S, T> ignoreIf(T trigger, FuncBoolean guard) {
assert guard != null : GUARD_IS_NULL;
representation.addTriggerBehaviour(new InternalTriggerBehaviour<S, T>(trigger, guard, NO_ACTION));
return this;
} | java | {
"resource": ""
} |
q166296 | StateMachineConfig.getOrCreateRepresentation | validation | private StateRepresentation<TState, TTrigger> getOrCreateRepresentation(TState state) {
StateRepresentation<TState, TTrigger> result = stateConfiguration.get(state);
if (result == null) {
result = new StateRepresentation<>(state);
stateConfiguration.put(state, result);
}
return result;
} | java | {
"resource": ""
} |
q166297 | LifeCycleManager.addInstance | validation | public void addInstance(Object instance)
throws Exception
{
State currentState = state.get();
if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) {
throw new IllegalStateException();
}
else {
startInstance(instance);
if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) {
managedInstances.add(instance);
}
}
} | java | {
"resource": ""
} |
q166298 | DenseHll.setOverflow | validation | private boolean setOverflow(int bucket, int overflow)
{
for (int i = 0; i < overflows; i++) {
if (overflowBuckets[i] == bucket) {
overflowValues[i] = (byte) overflow;
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q166299 | DenseHll.mergeWith | validation | public DenseHll mergeWith(DenseHll other)
{
if (indexBitLength != other.indexBitLength) {
throw new IllegalArgumentException(String.format(
"Cannot merge HLLs with different number of buckets: %s vs %s",
numberOfBuckets(indexBitLength),
numberOfBuckets(other.indexBitLength)));
}
int baseline = Math.max(this.baseline, other.baseline);
int baselineCount = 0;
int overflows = 0;
int[] overflowBuckets = new int[OVERFLOW_GROW_INCREMENT];
byte[] overflowValues = new byte[OVERFLOW_GROW_INCREMENT];
int numberOfBuckets = numberOfBuckets(indexBitLength);
for (int i = 0; i < numberOfBuckets; i++) {
int value = Math.max(getValue(i), other.getValue(i));
int delta = value - baseline;
if (delta == 0) {
baselineCount++;
}
else if (delta > MAX_DELTA) {
// grow overflows arrays if necessary
overflowBuckets = Ints.ensureCapacity(overflowBuckets, overflows + 1, OVERFLOW_GROW_INCREMENT);
overflowValues = Bytes.ensureCapacity(overflowValues, overflows + 1, OVERFLOW_GROW_INCREMENT);
overflowBuckets[overflows] = i;
overflowValues[overflows] = (byte) (delta - MAX_DELTA);
overflows++;
delta = MAX_DELTA;
}
setDelta(i, delta);
}
this.baseline = (byte) baseline;
this.baselineCount = baselineCount;
this.overflows = overflows;
this.overflowBuckets = overflowBuckets;
this.overflowValues = overflowValues;
// all baseline values in one of the HLLs lost to the values
// in the other HLL, so we need to adjust the final baseline
adjustBaselineIfNeeded();
return this;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.