_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q176700
AbstractAntJavaBasedPlay2Mojo.createProject
test
protected Project createProject() { final Project antProject = new Project(); final ProjectHelper helper = ProjectHelper.getProjectHelper(); antProject.addReference( ProjectHelper.PROJECTHELPER_REFERENCE, helper ); helper.getImportStack().addElement( "AntBuilder" ); // import checks that stack is not empty final BuildLogger logger = new NoBannerLogger(); logger.setMessageOutputLevel( Project.MSG_INFO ); logger.setOutputPrintStream( System.out ); logger.setErrorPrintStream( System.err ); antProject.addBuildListener( logger ); antProject.init(); antProject.getBaseDir(); return antProject; }
java
{ "resource": "" }
q176701
AbstractAntJavaBasedPlay2Mojo.addSystemProperty
test
protected void addSystemProperty( Java java, String propertyName, String propertyValue ) { Environment.Variable sysPropPlayHome = new Environment.Variable(); sysPropPlayHome.setKey( propertyName ); sysPropPlayHome.setValue( propertyValue ); java.addSysproperty( sysPropPlayHome ); }
java
{ "resource": "" }
q176702
AbstractAntJavaBasedPlay2Mojo.addSystemProperty
test
protected void addSystemProperty( Java java, String propertyName, File propertyValue ) { Environment.Variable sysPropPlayHome = new Environment.Variable(); sysPropPlayHome.setKey( propertyName ); sysPropPlayHome.setFile( propertyValue ); java.addSysproperty( sysPropPlayHome ); }
java
{ "resource": "" }
q176703
DirectoryChooserFragment.openNewFolderDialog
test
private void openNewFolderDialog() { @SuppressLint("InflateParams") final View dialogView = getActivity().getLayoutInflater().inflate( R.layout.dialog_new_folder, null); final TextView msgView = (TextView) dialogView.findViewById(R.id.msgText); final EditText editText = (EditText) dialogView.findViewById(R.id.editText); editText.setText(mNewDirectoryName); msgView.setText(getString(R.string.create_folder_msg, mNewDirectoryName)); final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) .setTitle(R.string.create_folder_label) .setView(dialogView) .setNegativeButton(R.string.cancel_label, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }) .setPositiveButton(R.string.confirm_label, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); mNewDirectoryName = editText.getText().toString(); final int msg = createFolder(); Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); } }) .show(); alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(editText.getText().length() != 0); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(final CharSequence charSequence, final int i, final int i2, final int i3) { } @Override public void onTextChanged(final CharSequence charSequence, final int i, final int i2, final int i3) { final boolean textNotEmpty = charSequence.length() != 0; alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(textNotEmpty); msgView.setText(getString(R.string.create_folder_msg, charSequence.toString())); } @Override public void afterTextChanged(final Editable editable) { } }); editText.setVisibility(mConfig.allowNewDirectoryNameModification() ? View.VISIBLE : View.GONE); }
java
{ "resource": "" }
q176704
DirectoryChooserFragment.changeDirectory
test
private void changeDirectory(final File dir) { if (dir == null) { debug("Could not change folder: dir was null"); } else if (!dir.isDirectory()) { debug("Could not change folder: dir is no directory"); } else { final File[] contents = dir.listFiles(); if (contents != null) { int numDirectories = 0; for (final File f : contents) { if (f.isDirectory()) { numDirectories++; } } mFilesInDir = new File[numDirectories]; mFilenames.clear(); for (int i = 0, counter = 0; i < numDirectories; counter++) { if (contents[counter].isDirectory()) { mFilesInDir[i] = contents[counter]; mFilenames.add(contents[counter].getName()); i++; } } Arrays.sort(mFilesInDir); Collections.sort(mFilenames); mSelectedDir = dir; mTxtvSelectedFolder.setText(dir.getAbsolutePath()); mListDirectoriesAdapter.notifyDataSetChanged(); mFileObserver = createFileObserver(dir.getAbsolutePath()); mFileObserver.startWatching(); debug("Changed directory to %s", dir.getAbsolutePath()); } else { debug("Could not change folder: contents of dir were null"); } } refreshButtonState(); }
java
{ "resource": "" }
q176705
DirectoryChooserFragment.refreshButtonState
test
private void refreshButtonState() { final Activity activity = getActivity(); if (activity != null && mSelectedDir != null) { mBtnConfirm.setEnabled(isValidFile(mSelectedDir)); getActivity().invalidateOptionsMenu(); } }
java
{ "resource": "" }
q176706
DirectoryChooserFragment.createFileObserver
test
private FileObserver createFileObserver(final String path) { return new FileObserver(path, FileObserver.CREATE | FileObserver.DELETE | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) { @Override public void onEvent(final int event, final String path) { debug("FileObserver received event %d", event); final Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { refreshDirectory(); } }); } } }; }
java
{ "resource": "" }
q176707
DirectoryChooserFragment.returnSelectedFolder
test
private void returnSelectedFolder() { if (mSelectedDir != null) { debug("Returning %s as result", mSelectedDir.getAbsolutePath()); mListener.foreach(new UnitFunction<OnFragmentInteractionListener>() { @Override public void apply(final OnFragmentInteractionListener f) { f.onSelectDirectory(mSelectedDir.getAbsolutePath()); } }); } else { mListener.foreach(new UnitFunction<OnFragmentInteractionListener>() { @Override public void apply(final OnFragmentInteractionListener f) { f.onCancelChooser(); } }); } }
java
{ "resource": "" }
q176708
DirectoryChooserFragment.createFolder
test
private int createFolder() { if (mNewDirectoryName != null && mSelectedDir != null && mSelectedDir.canWrite()) { final File newDir = new File(mSelectedDir, mNewDirectoryName); if (newDir.exists()) { return R.string.create_folder_error_already_exists; } else { final boolean result = newDir.mkdir(); if (result) { return R.string.create_folder_success; } else { return R.string.create_folder_error; } } } else if (mSelectedDir != null && !mSelectedDir.canWrite()) { return R.string.create_folder_error_no_write_access; } else { return R.string.create_folder_error; } }
java
{ "resource": "" }
q176709
DirectoryChooserFragment.isValidFile
test
private boolean isValidFile(final File file) { return (file != null && file.isDirectory() && file.canRead() && (mConfig.allowReadOnlyDirectory() || file.canWrite())); }
java
{ "resource": "" }
q176710
MonitoredActivity.startBackgroundJob
test
public void startBackgroundJob(int msgId, Runnable runnable) { // make the progress dialog uncancelable, so that we can guarantee // that the thread is done before the activity gets destroyed ProgressDialog dialog = ProgressDialog.show(this, null, getString(msgId), true, false); Job<Object> managedJob = new Job<Object>(runnable, dialog); managedJob.runBackgroundJob(); }
java
{ "resource": "" }
q176711
ConverterHtmlToSpanned.startList
test
private void startList(boolean isOrderedList, Attributes attributes) { boolean isIndentation = isIndentation(attributes); ParagraphType newType = isIndentation && isOrderedList ? ParagraphType.INDENTATION_OL : isIndentation && !isOrderedList ? ParagraphType.INDENTATION_UL : isOrderedList ? ParagraphType.NUMBERING : ParagraphType.BULLET; AccumulatedParagraphStyle currentStyle = mParagraphStyles.isEmpty() ? null : mParagraphStyles.peek(); if (currentStyle == null) { // no previous style found -> create new AccumulatedParagraphStyle with indentations of 1 AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle(newType, 1, 1); mParagraphStyles.push(newStyle); } else if (currentStyle.getType() == newType) { // same style found -> increase indentations by 1 currentStyle.setAbsoluteIndent(currentStyle.getAbsoluteIndent() + 1); currentStyle.setRelativeIndent(currentStyle.getRelativeIndent() + 1); } else { // different style found -> create new AccumulatedParagraphStyle with incremented indentations AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle(newType, currentStyle.getAbsoluteIndent() + 1, 1); mParagraphStyles.push(newStyle); } }
java
{ "resource": "" }
q176712
ConverterHtmlToSpanned.endList
test
private void endList(boolean orderedList) { if (!mParagraphStyles.isEmpty()) { AccumulatedParagraphStyle style = mParagraphStyles.peek(); ParagraphType type = style.getType(); if ((orderedList && (type.isNumbering() || type == ParagraphType.INDENTATION_OL)) || (!orderedList && (type.isBullet() || type == ParagraphType.INDENTATION_UL))) { // the end tag matches the current style int indent = style.getRelativeIndent(); if (indent > 1) { style.setRelativeIndent(indent - 1); style.setAbsoluteIndent(style.getAbsoluteIndent() - 1); } else { mParagraphStyles.pop(); } } else { // the end tag doesn't match the current style mParagraphStyles.pop(); endList(orderedList); // find the next matching style } } }
java
{ "resource": "" }
q176713
HighlightView.handleMotion
test
void handleMotion(int edge, float dx, float dy) { Rect r = computeLayout(); if (edge == GROW_NONE) { return; } else if (edge == MOVE) { // Convert to image space before sending to moveBy(). moveBy(dx * (mCropRect.width() / r.width()), dy * (mCropRect.height() / r.height())); } else { if (((GROW_LEFT_EDGE | GROW_RIGHT_EDGE) & edge) == 0) { dx = 0; } if (((GROW_TOP_EDGE | GROW_BOTTOM_EDGE) & edge) == 0) { dy = 0; } // Convert to image space before sending to growBy(). float xDelta = dx * (mCropRect.width() / r.width()); float yDelta = dy * (mCropRect.height() / r.height()); growBy((((edge & GROW_LEFT_EDGE) != 0) ? -1 : 1) * xDelta, (((edge & GROW_TOP_EDGE) != 0) ? -1 : 1) * yDelta); } }
java
{ "resource": "" }
q176714
HighlightView.getCropRect
test
public Rect getCropRect() { return new Rect((int) mCropRect.left, (int) mCropRect.top, (int) mCropRect.right, (int) mCropRect.bottom); }
java
{ "resource": "" }
q176715
HighlightView.computeLayout
test
private Rect computeLayout() { RectF r = new RectF(mCropRect.left, mCropRect.top, mCropRect.right, mCropRect.bottom); mMatrix.mapRect(r); return new Rect(Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom)); }
java
{ "resource": "" }
q176716
RTEditText.register
test
void register(RTEditTextListener listener, RTMediaFactory<RTImage, RTAudio, RTVideo> mediaFactory) { mListener = listener; mMediaFactory = mediaFactory; }
java
{ "resource": "" }
q176717
RTEditText.addSpanWatcher
test
private void addSpanWatcher() { Spannable spannable = getText(); if (spannable.getSpans(0, spannable.length(), getClass()) != null) { spannable.setSpan(this, 0, spannable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); } }
java
{ "resource": "" }
q176718
SpinnerItemAdapter.getView
test
@SuppressLint("ViewHolder") @Override public final View getView(int position, View convertView, ViewGroup parent) { View spinnerView = mInflater.inflate(mSpinnerId, parent, false); mParent = parent; TextView spinnerTitleView = (TextView) spinnerView.findViewById(R.id.title); updateSpinnerTitle(spinnerTitleView); return spinnerView; }
java
{ "resource": "" }
q176719
SpinnerItemAdapter.getDropDownView
test
@SuppressLint("InlinedApi") @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { SpinnerItem spinnerItem = mItems.get(position); spinnerItem.setOnChangedListener(this, position); // we can't use the convertView because it keeps handing us spinner layouts (mSpinnerId) View spinnerItemView = mInflater.inflate(mSpinnerItemId, parent, false); int key = (position << 16) + getItemViewType(position); mViewCache.put(key, spinnerItemView); bindView(position, spinnerItemView, spinnerItem); return spinnerItemView; }
java
{ "resource": "" }
q176720
ConverterSpannedToHtml.convert
test
public RTHtml<RTImage, RTAudio, RTVideo> convert(final Spanned text, RTFormat.Html rtFormat) { mText = text; mRTFormat = rtFormat; mOut = new StringBuilder(); mImages = new ArrayList<>(); mParagraphStyles.clear(); // convert paragraphs convertParagraphs(); return new RTHtml<>(rtFormat, mOut.toString(), mImages); }
java
{ "resource": "" }
q176721
ConverterSpannedToHtml.withinParagraph
test
private void withinParagraph(final Spanned text, int start, int end) { // create sorted set of CharacterStyles SortedSet<CharacterStyle> sortedSpans = new TreeSet<>((s1, s2) -> { int start1 = text.getSpanStart(s1); int start2 = text.getSpanStart(s2); if (start1 != start2) return start1 - start2; // span which starts first comes first int end1 = text.getSpanEnd(s1); int end2 = text.getSpanEnd(s2); if (end1 != end2) return end2 - end1; // longer span comes first // if the paragraphs have the same span [start, end] we compare their name // compare the name only because local + anonymous classes have no canonical name return s1.getClass().getName().compareTo(s2.getClass().getName()); }); List<CharacterStyle> spanList = Arrays.asList(text.getSpans(start, end, CharacterStyle.class)); sortedSpans.addAll(spanList); // process paragraphs/divs convertText(text, start, end, sortedSpans); }
java
{ "resource": "" }
q176722
MediaUtils.createUniqueFile
test
public static File createUniqueFile(File targetFolder, String originalFile, boolean keepOriginal) { String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(originalFile); return createUniqueFile(targetFolder, originalFile, mimeType, keepOriginal); }
java
{ "resource": "" }
q176723
MediaUtils.determineOriginalFile
test
public static String determineOriginalFile(Context context, Uri uri) throws IllegalArgumentException { String originalFile = null; if (uri != null) { // Picasa on Android >= 3.0 or other files using content providers if (uri.getScheme().startsWith("content")) { originalFile = getPathFromUri(context, uri); } // Picasa on Android < 3.0 if (uri.toString().matches("https?://\\w+\\.googleusercontent\\.com/.+")) { originalFile = uri.toString(); } // local storage if (uri.getScheme().startsWith("file")) { originalFile = uri.toString().substring(7); } if (isNullOrEmpty(originalFile)) { throw new IllegalArgumentException("File path was null"); } } else { throw new IllegalArgumentException("Image Uri was null!"); } return originalFile; }
java
{ "resource": "" }
q176724
ElementType.namespace
test
public String namespace(String name, boolean attribute) { int colon = name.indexOf(':'); if (colon == -1) { return attribute ? "" : theSchema.getURI(); } String prefix = name.substring(0, colon); if (prefix.equals("xml")) { return "http://www.w3.org/XML/1998/namespace"; } else { return ("urn:x-prefix:" + prefix).intern(); } }
java
{ "resource": "" }
q176725
ElementType.localName
test
public String localName(String name) { int colon = name.indexOf(':'); if (colon == -1) { return name; } else { return name.substring(colon + 1).intern(); } }
java
{ "resource": "" }
q176726
ElementType.setAttribute
test
public void setAttribute(AttributesImpl atts, String name, String type, String value) { if (name.equals("xmlns") || name.startsWith("xmlns:")) { return; } ; String namespace = namespace(name, true); String localName = localName(name); int i = atts.getIndex(name); if (i == -1) { name = name.intern(); if (type == null) type = "CDATA"; if (!type.equals("CDATA")) value = normalize(value); atts.addAttribute(namespace, localName, name, type, value); } else { if (type == null) type = atts.getType(i); if (!type.equals("CDATA")) value = normalize(value); atts.setAttribute(i, namespace, localName, name, type, value); } }
java
{ "resource": "" }
q176727
ElementType.setAttribute
test
public void setAttribute(String name, String type, String value) { setAttribute(theAtts, name, type, value); }
java
{ "resource": "" }
q176728
TTFAnalyzer.getFontName
test
static String getFontName(String filePath) { TTFRandomAccessFile in = null; try { RandomAccessFile file = new RandomAccessFile(filePath, "r"); in = new TTFRandomAccessFile(file); return getTTFFontName(in, filePath); } catch (IOException e) { return null; // Missing permissions or corrupted font file? } finally { IOUtils.closeQuietly(in); } }
java
{ "resource": "" }
q176729
TTFAnalyzer.getFontName
test
static String getFontName(AssetManager assets, String filePath) { TTFAssetInputStream in = null; try { InputStream file = assets.open(filePath, AssetManager.ACCESS_RANDOM); in = new TTFAssetInputStream(file); return getTTFFontName(in, filePath); } catch (FileNotFoundException e) { return null; // Missing permissions? } catch (IOException e) { return null; // Corrupted font file? } finally { IOUtils.closeQuietly(in); } }
java
{ "resource": "" }
q176730
ByteArrayOutputStream.needNewBuffer
test
private void needNewBuffer(int newcount) { if (currentBufferIndex < buffers.size() - 1) { //Recycling old buffer filledBufferSum += currentBuffer.length; currentBufferIndex++; currentBuffer = buffers.get(currentBufferIndex); } else { //Creating new buffer int newBufferSize; if (currentBuffer == null) { newBufferSize = newcount; filledBufferSum = 0; } else { newBufferSize = Math.max( currentBuffer.length << 1, newcount - filledBufferSum); filledBufferSum += currentBuffer.length; } currentBufferIndex++; currentBuffer = new byte[newBufferSize]; buffers.add(currentBuffer); } }
java
{ "resource": "" }
q176731
ByteArrayOutputStream.write
test
@Override public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } synchronized (this) { int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; while (remaining > 0) { int part = Math.min(remaining, currentBuffer.length - inBufferPos); System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; if (remaining > 0) { needNewBuffer(newcount); inBufferPos = 0; } } count = newcount; } }
java
{ "resource": "" }
q176732
ByteArrayOutputStream.write
test
@Override public synchronized void write(int b) { int inBufferPos = count - filledBufferSum; if (inBufferPos == currentBuffer.length) { needNewBuffer(count + 1); inBufferPos = 0; } currentBuffer[inBufferPos] = (byte) b; count++; }
java
{ "resource": "" }
q176733
ByteArrayOutputStream.write
test
public synchronized int write(InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); while (n != -1) { readCount += n; inBufferPos += n; count += n; if (inBufferPos == currentBuffer.length) { needNewBuffer(currentBuffer.length); inBufferPos = 0; } n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); } return readCount; }
java
{ "resource": "" }
q176734
ByteArrayOutputStream.writeTo
test
public synchronized void writeTo(OutputStream out) throws IOException { int remaining = count; for (byte[] buf : buffers) { int c = Math.min(buf.length, remaining); out.write(buf, 0, c); remaining -= c; if (remaining == 0) { break; } } }
java
{ "resource": "" }
q176735
ByteArrayOutputStream.toByteArray
test
public synchronized byte[] toByteArray() { int remaining = count; if (remaining == 0) { return EMPTY_BYTE_ARRAY; } byte newbuf[] = new byte[remaining]; int pos = 0; for (byte[] buf : buffers) { int c = Math.min(buf.length, remaining); System.arraycopy(buf, 0, newbuf, pos, c); pos += c; remaining -= c; if (remaining == 0) { break; } } return newbuf; }
java
{ "resource": "" }
q176736
HorizontalRTToolbar.setFontSize
test
@Override public void setFontSize(int size) { if (mFontSize != null) { if (size <= 0) { mFontSizeAdapter.updateSpinnerTitle(""); mFontSizeAdapter.setSelectedItem(0); mFontSize.setSelection(0); } else { size = Helper.convertSpToPx(size); mFontSizeAdapter.updateSpinnerTitle(Integer.toString(size)); for (int pos = 0; pos < mFontSizeAdapter.getCount(); pos++) { FontSizeSpinnerItem item = mFontSizeAdapter.getItem(pos); if (size == item.getFontSize()) { mFontSizeAdapter.setSelectedItem(pos); mFontSize.setSelection(pos); break; } } } } }
java
{ "resource": "" }
q176737
FilenameUtils.separatorsToUnix
test
public static String separatorsToUnix(String path) { if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) { return path; } return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); }
java
{ "resource": "" }
q176738
CropImageView.recomputeFocus
test
private void recomputeFocus(MotionEvent event) { for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); hv.setFocus(false); hv.invalidate(); } for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); int edge = hv.getHit(event.getX(), event.getY()); if (edge != HighlightView.GROW_NONE) { if (!hv.hasFocus()) { hv.setFocus(true); hv.invalidate(); } break; } } invalidate(); }
java
{ "resource": "" }
q176739
CropImageView.ensureVisible
test
private void ensureVisible(HighlightView hv) { Rect r = hv.mDrawRect; int panDeltaX1 = Math.max(0, mLeft - r.left); int panDeltaX2 = Math.min(0, mRight - r.right); int panDeltaY1 = Math.max(0, mTop - r.top); int panDeltaY2 = Math.min(0, mBottom - r.bottom); int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2; if (panDeltaX != 0 || panDeltaY != 0) { panBy(panDeltaX, panDeltaY); } }
java
{ "resource": "" }
q176740
CropImageView.centerBasedOnHighlightView
test
private void centerBasedOnHighlightView(HighlightView hv) { Rect drawRect = hv.mDrawRect; float width = drawRect.width(); float height = drawRect.height(); float thisWidth = getWidth(); float thisHeight = getHeight(); float z1 = thisWidth / width * .8F; float z2 = thisHeight / height * .8F; float zoom = Math.min(z1, z2); zoom = zoom * this.getScale(); zoom = Math.max(1F, zoom); if ((Math.abs(zoom - getScale()) / zoom) > .1) { float[] coordinates = new float[]{hv.mCropRect.centerX(), hv.mCropRect.centerY()}; getImageMatrix().mapPoints(coordinates); zoomTo(zoom, coordinates[0], coordinates[1], 300F); } ensureVisible(hv); }
java
{ "resource": "" }
q176741
HTMLScanner.resetDocumentLocator
test
public void resetDocumentLocator(String publicid, String systemid) { thePublicid = publicid; theSystemid = systemid; theLastLine = theLastColumn = theCurrentLine = theCurrentColumn = 0; }
java
{ "resource": "" }
q176742
RegexValidator.validate
test
public String validate(String value) { if (value == null) { return null; } for (int i = 0; i < patterns.length; i++) { Matcher matcher = patterns[i].matcher(value); if (matcher.matches()) { int count = matcher.groupCount(); if (count == 1) { return matcher.group(1); } StringBuffer buffer = new StringBuffer(); for (int j = 0; j < count; j++) { String component = matcher.group(j+1); if (component != null) { buffer.append(component); } } return buffer.toString(); } } return null; }
java
{ "resource": "" }
q176743
Schema.elementType
test
@SuppressLint("DefaultLocale") public void elementType(String name, int model, int memberOf, int flags) { ElementType e = new ElementType(name, model, memberOf, flags, this); theElementTypes.put(name.toLowerCase(), e); if (memberOf == M_ROOT) theRoot = e; }
java
{ "resource": "" }
q176744
Schema.attribute
test
public void attribute(String elemName, String attrName, String type, String value) { ElementType e = getElementType(elemName); if (e == null) { throw new Error("Attribute " + attrName + " specified for unknown element type " + elemName); } e.setAttribute(attrName, type, value); }
java
{ "resource": "" }
q176745
Schema.parent
test
public void parent(String name, String parentName) { ElementType child = getElementType(name); ElementType parent = getElementType(parentName); if (child == null) { throw new Error("No child " + name + " for parent " + parentName); } if (parent == null) { throw new Error("No parent " + parentName + " for child " + name); } child.setParent(parent); }
java
{ "resource": "" }
q176746
Schema.getElementType
test
@SuppressLint("DefaultLocale") public ElementType getElementType(String name) { return (ElementType) (theElementTypes.get(name.toLowerCase())); }
java
{ "resource": "" }
q176747
Schema.getEntity
test
public int getEntity(String name) { // System.err.println("%% Looking up entity " + name); Integer ch = (Integer) theEntities.get(name); if (ch == null) return 0; return ch.intValue(); }
java
{ "resource": "" }
q176748
Effects.cleanupParagraphs
test
public static void cleanupParagraphs(RTEditText editor, Effect...exclude) { cleanupParagraphs(editor, Effects.ALIGNMENT, exclude); cleanupParagraphs(editor, Effects.INDENTATION, exclude); cleanupParagraphs(editor, Effects.BULLET, exclude); cleanupParagraphs(editor, Effects.NUMBER, exclude); }
java
{ "resource": "" }
q176749
CharacterEffect.applyToSelection
test
public void applyToSelection(RTEditText editor, V value) { Selection selection = getSelection(editor); // SPAN_INCLUSIVE_INCLUSIVE is default for empty spans int flags = selection.isEmpty() ? Spanned.SPAN_INCLUSIVE_INCLUSIVE : Spanned.SPAN_EXCLUSIVE_INCLUSIVE; Spannable str = editor.getText(); for (RTSpan<V> span : getSpans(str, selection, SpanCollectMode.SPAN_FLAGS)) { boolean sameSpan = span.getValue().equals(value); int spanStart = str.getSpanStart(span); if (spanStart < selection.start()) { // process preceding spans if (sameSpan) { // we have a preceding span --> use SPAN_EXCLUSIVE_INCLUSIVE instead of SPAN_INCLUSIVE_INCLUSIVE flags = Spanned.SPAN_EXCLUSIVE_INCLUSIVE; selection.offset(selection.start() - spanStart, 0); } else { str.setSpan(newSpan(span.getValue()), spanStart, selection.start(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } int spanEnd = str.getSpanEnd(span); if (spanEnd > selection.end()) { // process succeeding spans if (sameSpan) { selection.offset(0, spanEnd - selection.end()); } else { str.setSpan(newSpan(span.getValue()), selection.end(), spanEnd, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } } str.removeSpan(span); } if (value != null) { RTSpan<V> newSpan = newSpan(value); if (newSpan != null) { str.setSpan(newSpan, selection.start(), selection.end(), flags); } } }
java
{ "resource": "" }
q176750
EmailValidator.isValidDomain
test
protected boolean isValidDomain(String domain) { // see if domain is an IP address in brackets Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain); if (ipDomainMatcher.matches()) { InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); return inetAddressValidator.isValid(ipDomainMatcher.group(1)); } // Domain is symbolic name DomainValidator domainValidator = DomainValidator.getInstance(allowLocal); return domainValidator.isValid(domain) || domainValidator.isValidTld(domain); }
java
{ "resource": "" }
q176751
RTOperationManager.executed
test
synchronized void executed(RTEditText editor, Operation op) { Stack<Operation> undoStack = getUndoStack(editor); Stack<Operation> redoStack = getRedoStack(editor); // if operations are executed in a quick succession we "merge" them to have but one // -> saves memory and makes more sense from a user perspective (each key stroke an undo? -> no way) while (!undoStack.empty() && op.canMerge(undoStack.peek())) { Operation previousOp = undoStack.pop(); op.merge(previousOp); } push(op, undoStack); redoStack.clear(); }
java
{ "resource": "" }
q176752
RTOperationManager.redo
test
synchronized void redo(RTEditText editor) { Stack<Operation> redoStack = getRedoStack(editor); if (!redoStack.empty()) { Stack<Operation> undoStack = getUndoStack(editor); Operation op = redoStack.pop(); push(op, undoStack); op.redo(editor); while (!redoStack.empty() && op.canMerge(redoStack.peek())) { op = redoStack.pop(); push(op, undoStack); op.redo(editor); } } }
java
{ "resource": "" }
q176753
ConverterTextToHtml.replaceAll
test
private static String replaceAll(String source, String search, String replace) { if (USE_REPLACE_ALL) { return source.replaceAll(search, replace); } else { Pattern p = Pattern.compile(search); Matcher m = p.matcher(source); StringBuffer sb = new StringBuffer(); boolean atLeastOneFound = false; while (m.find()) { m.appendReplacement(sb, replace); atLeastOneFound = true; } if (atLeastOneFound) { m.appendTail(sb); return sb.toString(); } else { return source; } } }
java
{ "resource": "" }
q176754
BitmapManager.getOrCreateThreadStatus
test
private synchronized ThreadStatus getOrCreateThreadStatus(Thread t) { ThreadStatus status = mThreadStatus.get(t); if (status == null) { status = new ThreadStatus(); mThreadStatus.put(t, status); } return status; }
java
{ "resource": "" }
q176755
BitmapManager.setDecodingOptions
test
private synchronized void setDecodingOptions(Thread t, BitmapFactory.Options options) { getOrCreateThreadStatus(t).mOptions = options; }
java
{ "resource": "" }
q176756
BitmapManager.canThreadDecoding
test
public synchronized boolean canThreadDecoding(Thread t) { ThreadStatus status = mThreadStatus.get(t); if (status == null) { // allow decoding by default return true; } return (status.mState != State.CANCEL); }
java
{ "resource": "" }
q176757
BitmapManager.decodeFileDescriptor
test
public Bitmap decodeFileDescriptor(FileDescriptor fd, BitmapFactory.Options options) { if (options.mCancel) { return null; } Thread thread = Thread.currentThread(); if (!canThreadDecoding(thread)) { return null; } setDecodingOptions(thread, options); Bitmap b = BitmapFactory.decodeFileDescriptor(fd, null, options); removeDecodingOptions(thread); return b; }
java
{ "resource": "" }
q176758
FontManager.getFonts
test
public static SortedSet<RTTypeface> getFonts(Context context) { /* * Fonts from the assets folder */ Map<String, String> assetFonts = getAssetFonts(context); AssetManager assets = context.getResources().getAssets(); for (String fontName : assetFonts.keySet()) { String filePath = assetFonts.get(fontName); if (!ALL_FONTS.contains(fontName)) { try { Typeface typeface = Typeface.createFromAsset(assets, filePath); ALL_FONTS.add(new RTTypeface(fontName, typeface)); } catch (Exception e) { // this can happen if we don't have access to the font or it's not a font or... } } } /* * Fonts from the system */ Map<String, String> systemFonts = getSystemFonts(); for (String fontName : systemFonts.keySet()) { String filePath = systemFonts.get(fontName); if (!ALL_FONTS.contains(fontName)) { try { Typeface typeface = Typeface.createFromFile(filePath); ALL_FONTS.add(new RTTypeface(fontName, typeface)); } catch (Exception e) { // this can happen if we don't have access to the font or it's not a font or... } } } return ALL_FONTS; }
java
{ "resource": "" }
q176759
FontManager.getAssetFonts
test
private static Map<String, String> getAssetFonts(Context context) { synchronized (ASSET_FONTS_BY_NAME) { /* * Let's do this only once because it's expensive and the result won't change in any case. */ if (ASSET_FONTS_BY_NAME.isEmpty()) { AssetManager assets = context.getResources().getAssets(); Collection<String> fontFiles = AssetIndex.getAssetIndex(context); if (fontFiles == null || fontFiles.isEmpty()) { fontFiles = listFontFiles(context.getResources()); } for (String filePath : fontFiles) { if (filePath.toLowerCase(Locale.getDefault()).endsWith("ttf")) { String fontName = TTFAnalyzer.getFontName(assets, filePath); if (fontName == null) { fontName = getFileName(filePath); } ASSET_FONTS_BY_NAME.put(fontName, filePath); } } } return ASSET_FONTS_BY_NAME; } }
java
{ "resource": "" }
q176760
FontManager.getSystemFonts
test
private static Map<String, String> getSystemFonts() { synchronized (SYSTEM_FONTS_BY_NAME) { for (String fontDir : FONT_DIRS) { File dir = new File(fontDir); if (!dir.exists()) continue; File[] files = dir.listFiles(); if (files == null) continue; for (File file : files) { String filePath = file.getAbsolutePath(); if (!SYSTEM_FONTS_BY_PATH.containsKey(filePath)) { String fontName = TTFAnalyzer.getFontName(file.getAbsolutePath()); if (fontName == null) { fontName = getFileName(filePath); } SYSTEM_FONTS_BY_PATH.put(filePath, fontName); SYSTEM_FONTS_BY_NAME.put(fontName, filePath); } } } return SYSTEM_FONTS_BY_NAME; } }
java
{ "resource": "" }
q176761
Parser.setup
test
private void setup() { if (theSchema == null) theSchema = new HTMLSchema(); if (theScanner == null) theScanner = new HTMLScanner(); if (theAutoDetector == null) { theAutoDetector = new AutoDetector() { public Reader autoDetectingReader(InputStream i) { return new InputStreamReader(i); } }; } theStack = new Element(theSchema.getElementType("<root>"), defaultAttributes); thePCDATA = new Element(theSchema.getElementType("<pcdata>"), defaultAttributes); theNewElement = null; theAttributeName = null; thePITarget = null; theSaved = null; theEntity = 0; virginStack = true; theDoctypeName = theDoctypePublicId = theDoctypeSystemId = null; }
java
{ "resource": "" }
q176762
Parser.getReader
test
private Reader getReader(InputSource s) throws SAXException, IOException { Reader r = s.getCharacterStream(); InputStream i = s.getByteStream(); String encoding = s.getEncoding(); String publicid = s.getPublicId(); String systemid = s.getSystemId(); if (r == null) { if (i == null) i = getInputStream(publicid, systemid); // i = new BufferedInputStream(i); if (encoding == null) { r = theAutoDetector.autoDetectingReader(i); } else { try { r = new InputStreamReader(i, encoding); } catch (UnsupportedEncodingException e) { r = new InputStreamReader(i); } } } // r = new BufferedReader(r); return r; }
java
{ "resource": "" }
q176763
Parser.getInputStream
test
private InputStream getInputStream(String publicid, String systemid) throws IOException, SAXException { URL basis = new URL("file", "", System.getProperty("user.dir") + "/."); URL url = new URL(basis, systemid); URLConnection c = url.openConnection(); return c.getInputStream(); }
java
{ "resource": "" }
q176764
Parser.adup
test
@Override public void adup(char[] buff, int offset, int length) throws SAXException { if (theNewElement != null && theAttributeName != null) { theNewElement.setAttribute(theAttributeName, null, theAttributeName); theAttributeName = null; } }
java
{ "resource": "" }
q176765
Parser.expandEntities
test
private String expandEntities(String src) { int refStart = -1; int len = src.length(); char[] dst = new char[len]; int dstlen = 0; for (int i = 0; i < len; i++) { char ch = src.charAt(i); dst[dstlen++] = ch; if (ch == '&' && refStart == -1) { // start of a ref excluding & refStart = dstlen; } else if (refStart == -1) { // not in a ref } else if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '#') { // valid entity char } else if (ch == ';') { // properly terminated ref int ent = lookupEntity(dst, refStart, dstlen - refStart - 1); if (ent > 0xFFFF) { ent -= 0x10000; dst[refStart - 1] = (char) ((ent >> 10) + 0xD800); dst[refStart] = (char) ((ent & 0x3FF) + 0xDC00); dstlen = refStart + 1; } else if (ent != 0) { dst[refStart - 1] = (char) ent; dstlen = refStart; } refStart = -1; } else { // improperly terminated ref refStart = -1; } } return new String(dst, 0, dstlen); }
java
{ "resource": "" }
q176766
Parser.lookupEntity
test
private int lookupEntity(char[] buff, int offset, int length) { int result = 0; if (length < 1) return result; // length) + "]"); if (buff[offset] == '#') { if (length > 1 && (buff[offset + 1] == 'x' || buff[offset + 1] == 'X')) { try { return Integer.parseInt(new String(buff, offset + 2, length - 2), 16); } catch (NumberFormatException e) { return 0; } } try { return Integer.parseInt( new String(buff, offset + 1, length - 1), 10); } catch (NumberFormatException e) { return 0; } } return theSchema.getEntity(new String(buff, offset, length)); }
java
{ "resource": "" }
q176767
Parser.restart
test
private void restart(Element e) throws SAXException { while (theSaved != null && theStack.canContain(theSaved) && (e == null || theSaved.canContain(e))) { Element next = theSaved.next(); push(theSaved); theSaved = next; } }
java
{ "resource": "" }
q176768
Parser.pop
test
private void pop() throws SAXException { if (theStack == null) return; // empty stack String name = theStack.name(); String localName = theStack.localName(); String namespace = theStack.namespace(); String prefix = prefixOf(name); if (!namespaces) namespace = localName = ""; theContentHandler.endElement(namespace, localName, name); if (foreign(prefix, namespace)) { theContentHandler.endPrefixMapping(prefix); // "] for elements to " + namespace); } Attributes atts = theStack.atts(); for (int i = atts.getLength() - 1; i >= 0; i--) { String attNamespace = atts.getURI(i); String attPrefix = prefixOf(atts.getQName(i)); if (foreign(attPrefix, attNamespace)) { theContentHandler.endPrefixMapping(attPrefix); // "] for attributes to " + attNamespace); } } theStack = theStack.next(); }
java
{ "resource": "" }
q176769
Parser.restartablyPop
test
private void restartablyPop() throws SAXException { Element popped = theStack; pop(); if (restartElements && (popped.flags() & Schema.F_RESTART) != 0) { popped.anonymize(); popped.setNext(theSaved); theSaved = popped; } }
java
{ "resource": "" }
q176770
Parser.prefixOf
test
private String prefixOf(String name) { int i = name.indexOf(':'); String prefix = ""; if (i != -1) prefix = name.substring(0, i); return prefix; }
java
{ "resource": "" }
q176771
Parser.foreign
test
private boolean foreign(String prefix, String namespace) { // " for foreignness -- "); boolean foreign = !(prefix.equals("") || namespace.equals("") || namespace.equals(theSchema.getURI())); return foreign; }
java
{ "resource": "" }
q176772
Parser.trimquotes
test
private static String trimquotes(String in) { if (in == null) return in; int length = in.length(); if (length == 0) return in; char s = in.charAt(0); char e = in.charAt(length - 1); if (s == e && (s == '\'' || s == '"')) { in = in.substring(1, in.length() - 1); } return in; }
java
{ "resource": "" }
q176773
Parser.split
test
private static String[] split(String val) throws IllegalArgumentException { val = val.trim(); if (val.length() == 0) { return new String[0]; } else { ArrayList<String> l = new ArrayList<String>(); int s = 0; int e = 0; boolean sq = false; // single quote boolean dq = false; // double quote char lastc = 0; int len = val.length(); for (e = 0; e < len; e++) { char c = val.charAt(e); if (!dq && c == '\'' && lastc != '\\') { sq = !sq; if (s < 0) s = e; } else if (!sq && c == '\"' && lastc != '\\') { dq = !dq; if (s < 0) s = e; } else if (!sq && !dq) { if (Character.isWhitespace(c)) { if (s >= 0) l.add(val.substring(s, e)); s = -1; } else if (s < 0 && c != ' ') { s = e; } } lastc = c; } l.add(val.substring(s, e)); return (String[]) l.toArray(new String[0]); } }
java
{ "resource": "" }
q176774
Parser.rectify
test
private void rectify(Element e) throws SAXException { Element sp; while (true) { for (sp = theStack; sp != null; sp = sp.next()) { if (sp.canContain(e)) break; } if (sp != null) break; ElementType parentType = e.parent(); if (parentType == null) break; Element parent = new Element(parentType, defaultAttributes); // parent.name()); parent.setNext(e); e = parent; } if (sp == null) return; // don't know what to do while (theStack != sp) { if (theStack == null || theStack.next() == null || theStack.next().next() == null) break; restartablyPop(); } while (e != null) { Element nexte = e.next(); if (!e.name().equals("<pcdata>")) push(e); e = nexte; restart(e); } theNewElement = null; }
java
{ "resource": "" }
q176775
Parser.makeName
test
private String makeName(char[] buff, int offset, int length) { StringBuffer dst = new StringBuffer(length + 2); boolean seenColon = false; boolean start = true; // String src = new String(buff, offset, length); // DEBUG for (; length-- > 0; offset++) { char ch = buff[offset]; if (Character.isLetter(ch) || ch == '_') { start = false; dst.append(ch); } else if (Character.isDigit(ch) || ch == '-' || ch == '.') { if (start) dst.append('_'); start = false; dst.append(ch); } else if (ch == ':' && !seenColon) { seenColon = true; if (start) dst.append('_'); start = true; dst.append(translateColons ? '_' : ch); } } int dstLength = dst.length(); if (dstLength == 0 || dst.charAt(dstLength - 1) == ':') dst.append('_'); return dst.toString().intern(); }
java
{ "resource": "" }
q176776
RTManager.onSaveInstanceState
test
public void onSaveInstanceState(Bundle outState) { outState.putString("mToolbarVisibility", mToolbarVisibility.name()); outState.putBoolean("mToolbarIsVisible", mToolbarIsVisible); outState.putInt("mActiveEditor", mActiveEditor); if (mLinkSelection != null) { outState.putSerializable("mLinkSelection", mLinkSelection); } }
java
{ "resource": "" }
q176777
RTManager.onDestroy
test
public void onDestroy(boolean isSaved) { EventBus.getDefault().unregister(this); for (RTEditText editor : mEditors.values()) { editor.unregister(); editor.onDestroy(isSaved); } mEditors.clear(); for (RTToolbar toolbar : mToolbars.values()) { toolbar.removeToolbarListener(); } mToolbars.clear(); mRTApi = null; }
java
{ "resource": "" }
q176778
RTManager.onEventMainThread
test
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onEventMainThread(MediaEvent event) { RTEditText editor = mEditors.get(mActiveEditor); RTMedia media = event.getMedia(); if (editor != null && media instanceof RTImage) { insertImage(editor, (RTImage) media); EventBus.getDefault().removeStickyEvent(event); mActiveEditor = Integer.MAX_VALUE; } }
java
{ "resource": "" }
q176779
RTManager.onEventMainThread
test
@Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(LinkEvent event) { final String fragmentTag = event.getFragmentTag(); mRTApi.removeFragment(fragmentTag); if (!event.wasCancelled() && ID_01_LINK_FRAGMENT.equals(fragmentTag)) { RTEditText editor = getActiveEditor(); if (editor != null) { Link link = event.getLink(); String url = null; if (link != null && link.isValid()) { // the mLinkSelection.end() <= editor.length() check is necessary since // the editor text can change when the link fragment is open Selection selection = mLinkSelection != null && mLinkSelection.end() <= editor.length() ? mLinkSelection : new Selection(editor); String linkText = link.getLinkText(); // if no text is selected this inserts the entered link text // if text is selected we replace it by the link text Editable str = editor.getText(); str.replace(selection.start(), selection.end(), linkText); editor.setSelection(selection.start(), selection.start() + linkText.length()); url = link.getUrl(); } editor.applyEffect(Effects.LINK, url); // if url == null -> remove the link } } }
java
{ "resource": "" }
q176780
ImageViewTouchBase.getProperBaseMatrix
test
private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) { float viewWidth = getWidth(); float viewHeight = getHeight(); float w = bitmap.getWidth(); float h = bitmap.getHeight(); matrix.reset(); // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math.min(viewWidth / w, 2.0f); float heightScale = Math.min(viewHeight / h, 2.0f); float scale = Math.min(widthScale, heightScale); matrix.postConcat(bitmap.getRotateMatrix()); matrix.postScale(scale, scale); matrix.postTranslate((viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F); }
java
{ "resource": "" }
q176781
ImageViewTouchBase.maxZoom
test
protected float maxZoom() { if (mBitmapDisplayed.getBitmap() == null) { return 1F; } float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth; float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight; float max = Math.max(fw, fh) * 4; return max; }
java
{ "resource": "" }
q176782
Effect.existsInSelection
test
final public boolean existsInSelection(RTEditText editor) { Selection selection = getSelection(editor); List<RTSpan<V>> spans = getSpans(editor.getText(), selection, SpanCollectMode.SPAN_FLAGS); return ! spans.isEmpty(); }
java
{ "resource": "" }
q176783
ParagraphEffect.findSpans2Remove
test
protected void findSpans2Remove(Spannable str, Paragraph paragraph, ParagraphSpanProcessor<V> spanProcessor) { List<RTSpan<V>> spans = getSpans(str, paragraph, SpanCollectMode.EXACT); spanProcessor.removeSpans(spans, paragraph); }
java
{ "resource": "" }
q176784
Helper.encodeUrl
test
public static String encodeUrl(String url) { Uri uri = Uri.parse(url); try { Map<String, List<String>> splitQuery = splitQuery(uri); StringBuilder encodedQuery = new StringBuilder(); for (String key : splitQuery.keySet()) { for (String value : splitQuery.get(key)) { if (encodedQuery.length() > 0) { encodedQuery.append("&"); } encodedQuery.append(key + "=" + URLEncoder.encode(value, "UTF-8")); } } String queryString = encodedQuery != null && encodedQuery.length() > 0 ? "?" + encodedQuery : ""; URI baseUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment()); return baseUri + queryString; } catch (UnsupportedEncodingException ignore) {} catch (URISyntaxException ignore) {} return uri.toString(); }
java
{ "resource": "" }
q176785
Helper.decodeQuery
test
public static String decodeQuery(String url) { try { return URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException ignore) {} return url; }
java
{ "resource": "" }
q176786
FileHelper.pickDirectory
test
public static boolean pickDirectory(Activity activity, File startPath, int requestCode) { PackageManager packageMgr = activity.getPackageManager(); for (String[] intent : PICK_DIRECTORY_INTENTS) { String intentAction = intent[0]; String uriPrefix = intent[1]; Intent startIntent = new Intent(intentAction) .putExtra("org.openintents.extra.TITLE", activity.getString(R.string.save_as)) .setData(Uri.parse(uriPrefix + startPath.getPath())); try { if (startIntent.resolveActivity(packageMgr) != null) { activity.startActivityForResult(startIntent, requestCode); return true; } } catch (ActivityNotFoundException e) { showNoFilePickerError(activity, e); } } return false; }
java
{ "resource": "" }
q176787
CropImageActivity.rotateImage
test
private Bitmap rotateImage(Bitmap src, float degree) { // create new matrix Matrix matrix = new Matrix(); // setup rotation degree matrix.postRotate(degree); Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true); return bmp; }
java
{ "resource": "" }
q176788
HTMLWriter.setOutput
test
public void setOutput(Writer writer) { if (writer == null) { output = new OutputStreamWriter(System.out); } else { output = writer; } }
java
{ "resource": "" }
q176789
HTMLWriter.write
test
private void write(char c) throws SAXException { try { output.write(c); } catch (IOException e) { throw new SAXException(e); } }
java
{ "resource": "" }
q176790
HTMLWriter.write
test
private void write(String s) throws SAXException { try { output.write(s); } catch (IOException e) { throw new SAXException(e); } }
java
{ "resource": "" }
q176791
HTMLWriter.booleanAttribute
test
private boolean booleanAttribute(String localName, String qName, String value) { String name = localName; if (name == null) { int i = qName.indexOf(':'); if (i != -1) name = qName.substring(i + 1, qName.length()); } if (!name.equals(value)) return false; for (int j = 0; j < booleans.length; j++) { if (name.equals(booleans[j])) return true; } return false; }
java
{ "resource": "" }
q176792
HTMLWriter.writeEscUTF16
test
private void writeEscUTF16(String s, int start, int length, boolean isAttVal) throws SAXException { String subString = s.substring(start, start + length); write(StringEscapeUtils.escapeHtml4(subString)); }
java
{ "resource": "" }
q176793
HTMLWriter.writeNSDecls
test
@SuppressWarnings("unchecked") private void writeNSDecls() throws SAXException { Enumeration<String> prefixes = (Enumeration<String>) nsSupport.getDeclaredPrefixes(); while (prefixes.hasMoreElements()) { String prefix = (String) prefixes.nextElement(); String uri = nsSupport.getURI(prefix); if (uri == null) { uri = ""; } write(' '); if ("".equals(prefix)) { write("xmlns=\""); } else { write("xmlns:"); write(prefix); write("=\""); } writeEscUTF16(uri, 0, uri.length(), true); write('\"'); } }
java
{ "resource": "" }
q176794
HTMLWriter.writeName
test
private void writeName(String uri, String localName, String qName, boolean isElement) throws SAXException { String prefix = doPrefix(uri, qName, isElement); if (prefix != null && !"".equals(prefix)) { write(prefix); write(':'); } if (localName != null && !"".equals(localName)) { write(localName); } else { int i = qName.indexOf(':'); write(qName.substring(i + 1, qName.length())); } }
java
{ "resource": "" }
q176795
AwsKinesisUtils.createStreamIfNotExists
test
private static void createStreamIfNotExists(AmazonKinesis kinesis, String streamName, int shardCount) { performAmazonActionWithRetry("createStream", () -> { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(streamName).withLimit(1); try { kinesis.describeStream(describeStreamRequest); } catch (ResourceNotFoundException e) { kinesis.createStream(streamName, shardCount); } return null; }, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_DURATION_IN_MILLIS); }
java
{ "resource": "" }
q176796
AwsKinesisUtils.waitStreamActivation
test
private static void waitStreamActivation(AmazonKinesis consumer, String streamName, long streamCreationTimeoutMillis) { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(streamName).withLimit(1); DescribeStreamResult describeStreamResult = null; String streamStatus = null; long endTime = System.currentTimeMillis() + streamCreationTimeoutMillis; do { try { describeStreamResult = consumer.describeStream(describeStreamRequest); streamStatus = describeStreamResult.getStreamDescription().getStreamStatus(); if (ACTIVE_STREAM_STATUS.equals(streamStatus)) { break; } Thread.sleep(100); } catch (ResourceNotFoundException | LimitExceededException ignored) { // ignored } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AwsKinesisException("Thread interrupted while waiting for stream activation", args -> args.add("streamName", streamName), e); } } while (System.currentTimeMillis() < endTime); if (describeStreamResult == null || streamStatus == null || !streamStatus.equals(ACTIVE_STREAM_STATUS)) { throw new AwsKinesisException("Stream never went active", args -> args.add("streamName", streamName).add("streamCreationTimeoutMillis", streamCreationTimeoutMillis)); } }
java
{ "resource": "" }
q176797
IronMigration.completeStoreSnapshotWithMissingInstanceSnapshots
test
private static void completeStoreSnapshotWithMissingInstanceSnapshots(Path targetStoresPath) { String transactionIdRegexAlone = "\"transactionId\"\\s*:\\s*\\d+\\s*,"; String transactionIdRegexReplace = "(.*\"transactionId\"\\s*:\\s*)\\d+(\\s*,.*)"; Pattern transactionIdPattern = compile(transactionIdRegexAlone); Set<File> previousSnapshots = new HashSet<>(); Arrays.stream(targetStoresPath.resolve(SNAPSHOT_DIRECTORY_NAME).toFile().listFiles()). sorted(). forEach(snapshot -> { Set<String> snapshotNames = Arrays.stream(snapshot.listFiles()).map(File::getName).collect(toSet()); previousSnapshots.stream(). filter(previousSnapshot -> !snapshotNames.contains(previousSnapshot.getName())). forEach(previousSnapshot -> { try { Path targetPath = snapshot.toPath().resolve(previousSnapshot.getName()); Path sourcePath = previousSnapshot.toPath(); long count = countTransactionId(transactionIdPattern, sourcePath); if (count != 1L) { throw new StoreException("transactionId not found once", args -> args.add("found count", count)); } BigInteger newTransactionId = new BigInteger(snapshot.getName()); replaceTransactionIdValue(transactionIdRegexReplace, sourcePath, targetPath, newTransactionId.toString()); } catch (IOException e) { throw new UncheckedIOException(e); } }); previousSnapshots.clear(); previousSnapshots.addAll(Arrays.stream(snapshot.listFiles()).collect(toSet())); }); }
java
{ "resource": "" }
q176798
AwsKinesisTransactionStore.waitTheMinimalDurationToExecuteTheNextProvisioningRequest
test
private boolean waitTheMinimalDurationToExecuteTheNextProvisioningRequest() { if (m_lastGetShardIteratorRequestTime != null) { long delay = m_durationBetweenRequests.get() - (System.currentTimeMillis() - m_lastGetShardIteratorRequestTime); if (delay > 0) { try { Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } } m_lastGetShardIteratorRequestTime = System.currentTimeMillis(); return true; }
java
{ "resource": "" }
q176799
AwsKinesisTransactionStore.getRecords
test
@Nullable private List<Record> getRecords(GetRecordsRequest getRecordsRequest) { return tryAmazonAction("", () -> { GetRecordsResult getRecordsResult = m_kinesis.getRecords(getRecordsRequest); m_shardIterator = getRecordsResult.getNextShardIterator(); List<Record> records = getRecordsResult.getRecords(); LOG.trace("Get records", args -> args.add("streamName", m_streamName).add("record number", records.size()) .add("millisBehindLatest", getRecordsResult.getMillisBehindLatest())); return records; }, m_durationBetweenRequests).orElse(List.of()); }
java
{ "resource": "" }