_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q169000 | XMLIndent.addEmptyTag | validation | @Override
public void addEmptyTag(String tagName)
{
_xml.addXML(_indent.toString());
_xml.addEmptyTag(tagName);
_xml.addXML("\n");
} | java | {
"resource": ""
} |
q169001 | XMLIndent.addOpeningTag | validation | @Override
public void addOpeningTag(String tagName, Map attributes)
{
_xml.addXML(_indent.toString());
_xml.addOpeningTag(tagName, attributes);
_xml.addXML("\n");
_indent.inc();
} | java | {
"resource": ""
} |
q169002 | IOUtils.deleteFile | validation | public static boolean deleteFile(File file) throws IOException
{
if(!file.exists())
return false;
File[] files = file.listFiles();
if(files != null)
{
for(int i = 0; i < files.length; i++)
{
File childFile = files[i];
if(childFile.equals(file))
continue;
if(childFile.isDirectory())
deleteFile(childFile);
else
childFile.delete();
}
}
return file.delete();
} | java | {
"resource": ""
} |
q169003 | IOUtils.createTempDirectory | validation | public static File createTempDirectory(String namespace, String name) throws IOException
{
File dir = File.createTempFile(namespace, "");
if(dir.exists())
deleteFile(dir);
createNewDirectory(dir);
File tempDir = new File(dir, name);
createNewDirectory(tempDir);
return tempDir.getCanonicalFile();
} | java | {
"resource": ""
} |
q169004 | ReflectUtils.getProxiedObject | validation | @SuppressWarnings("unchecked")
public static Object getProxiedObject(Object proxy)
{
if(Proxy.isProxyClass(proxy.getClass()))
{
InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy);
if(invocationHandler instanceof ObjectProxy)
{
ObjectProxy objectProxy = (ObjectProxy) invocationHandler;
// recursively fetch the proxy
return getProxiedObject(objectProxy.getProxiedObject());
}
else
return proxy;
}
else
return proxy;
} | java | {
"resource": ""
} |
q169005 | ReflectUtils.forName | validation | public static Class forName(Class clazz, ClassLoader classLoader)
throws ClassNotFoundException, LinkageError
{
if(clazz == null)
return null;
if(classLoader == null)
{
classLoader = getDefaultClassLoader();
}
if(clazz.getClassLoader() == null || clazz.getClassLoader().equals(classLoader))
return clazz;
else
return forName(clazz.getName(), classLoader);
} | java | {
"resource": ""
} |
q169006 | ReflectUtils.computeSignature | validation | @SuppressWarnings("unchecked")
public static String computeSignature(Method m)
{
StringBuilder sb = new StringBuilder();
sb.append(m.getName()).append('(');
Class[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
{
if(i > 0)
sb.append(',');
Class parameterType = parameterTypes[i];
sb.append(parameterType.getName());
}
sb.append(')');
return sb.toString();
} | java | {
"resource": ""
} |
q169007 | OneWayMessageDigestCodec.createWellKnownInstance | validation | private static OneWayMessageDigestCodec createWellKnownInstance(String algorithm,
String password,
OneWayCodec codec)
{
try
{
return new OneWayMessageDigestCodec(algorithm, password, codec);
}
catch(NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
catch(CloneNotSupportedException e)
{
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q169008 | URLBuilder.reset | validation | public void reset()
{
_scheme = null;
_userInfo = null;
_host = null;
_port = -1;
_path = null;
_query = new QueryBuilder();
_fragment = null;
_escapeFragment = true;
} | java | {
"resource": ""
} |
q169009 | URLBuilder.createFromPath | validation | public static URLBuilder createFromPath(String path)
{
URLBuilder res = new URLBuilder();
res.setPath(path);
return res;
} | java | {
"resource": ""
} |
q169010 | URLBuilder.addQueryParameter | validation | public static URL addQueryParameter(URL url, String name, String value)
{
URLBuilder ub = createFromURL(url);
ub.addQueryParameter(name, value);
return ub;
} | java | {
"resource": ""
} |
q169011 | QueryBuilder.getParameter | validation | @Override
public String getParameter(String name)
{
String[] params = getParameterValues(name);
if(params == null)
return null;
return params[0];
} | java | {
"resource": ""
} |
q169012 | QueryBuilder.addQueryParameter | validation | private void addQueryParameter(String name, String value)
{
if(_query.length() > 0)
_query.append('&');
_query.append(encode(name));
_query.append('=');
_query.append(encode(value));
} | java | {
"resource": ""
} |
q169013 | QueryBuilder.addParameters | validation | public void addParameters(Map<String, String[]> parameters)
{
for(Map.Entry<String, String[]> entry : parameters.entrySet())
{
addParameters(entry.getKey(), entry.getValue());
}
} | java | {
"resource": ""
} |
q169014 | QueryBuilder.addIndexedParameter | validation | public void addIndexedParameter(String name, int value, int index)
{
addParameter(getIndexedParamName(name, index), value);
} | java | {
"resource": ""
} |
q169015 | QueryBuilder.addQuery | validation | public void addQuery(URI uri)
{
try
{
addQuery(uri.getRawQuery(), false);
}
catch(URISyntaxException e)
{
// should not happen!
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q169016 | QueryBuilder.validateQuery | validation | private void validateQuery(String query) throws URISyntaxException
{
if(query.length() == 0)
return;
Iterator<String> iter = SS.splitToIterator(query);
while(iter.hasNext())
{
String s = iter.next();
if(s.length() > 0)
{
int idx = s.indexOf('=');
if(idx == -1)
throw new URISyntaxException(query, "missing equal sign in " + s);
if(s.lastIndexOf('=') != idx)
throw new URISyntaxException(query, "extra equal sign in " + s);
}
}
} | java | {
"resource": ""
} |
q169017 | QueryBuilder.addQuery | validation | public void addQuery(Query query)
{
if(query == null)
return;
try
{
if(!query.getEncoding().equals(getEncoding()))
throw new RuntimeException("TODO");
addQuery(query.getQuery(), false);
}
catch(URISyntaxException e)
{
// shouldn't happen since a query is already properly formatted
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q169018 | QueryBuilder.rebuildQuery | validation | private void rebuildQuery()
{
Map<String, String[]> map = getMap();
// reset query instance and re-populate it again
_query.setLength(0);
for (String key : map.keySet())
{
String[] parameters = map.get(key);
for (String param : parameters)
{
addQueryParameter(key, param);
}
}
} | java | {
"resource": ""
} |
q169019 | QueryBuilder.replaceParameter | validation | public String[] replaceParameter(String name, String value)
{
Map<String, String[]> map = getMap();
String[] v = map.put(name, new String[] { value });
rebuildQuery();
return v;
} | java | {
"resource": ""
} |
q169020 | ShutdownProxy.invoke | validation | @Override
public Object invoke(Object o, Method method, Object[] objects)
throws Throwable
{
// throws ShutdownRequestedException when in shutdown mode
_shutdown.startCall();
try
{
return method.invoke(_object, objects);
}
catch(InvocationTargetException e)
{
Throwable th = e.getTargetException();
try
{
throw th;
}
catch(Exception ex)
{
throw ex;
}
catch(Throwable throwable)
{
log.error(method.toString(), throwable);
throw throwable;
}
}
finally
{
_shutdown.endCall();
}
} | java | {
"resource": ""
} |
q169021 | ShutdownProxy.createShutdownProxy | validation | public static Object createShutdownProxy(Object o,
Class[] interfaces,
Shutdown shutdown)
{
if(interfaces == null)
interfaces = ReflectUtils.extractAllInterfaces(o);
return Proxy.newProxyInstance(o.getClass().getClassLoader(),
interfaces,
new ShutdownProxy(o, shutdown));
} | java | {
"resource": ""
} |
q169022 | LangUtils.convertToBoolean | validation | public static boolean convertToBoolean(Object o)
{
if(o == null)
return false;
if(o instanceof Boolean)
{
return (Boolean) o;
}
return convertToBoolean(o.toString());
} | java | {
"resource": ""
} |
q169023 | LangUtils.getStackTrace | validation | public static String getStackTrace(Throwable th)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
return sw.toString();
} | java | {
"resource": ""
} |
q169024 | PathUtils.removeTrailingSlash | validation | public static String removeTrailingSlash(String path)
{
if(path.endsWith("/"))
return path.substring(0, path.length() - 1);
else
return path;
} | java | {
"resource": ""
} |
q169025 | Shutdown.waitForShutdown | validation | @Override
public void waitForShutdown(Object timeout)
throws InterruptedException, IllegalStateException, TimeoutException
{
if(!_shutdown) throw new IllegalStateException("call shutdown first");
pendingCallsCount.waitForCounter(timeout);
} | java | {
"resource": ""
} |
q169026 | XML.addEmptyTag | validation | @Override
public void addEmptyTag(String tagName, Map attributes)
{
_xml.append('<').append(tagName);
addAttributes(attributes);
_xml.append(" />");
} | java | {
"resource": ""
} |
q169027 | XML.addAttribute | validation | private void addAttribute(String attrName, String attrValue)
{
if(attrName == null)
return;
_xml.append(' ');
_xml.append(attrName).append("=\"");
_xml.append(XMLUtils.xmlEncode(attrValue)).append('"');
} | java | {
"resource": ""
} |
q169028 | XML.addAttributes | validation | private void addAttributes(Map attributes)
{
if(attributes == null)
return;
Iterator iter = attributes.keySet().iterator();
while(iter.hasNext())
{
String attrName = (String) iter.next();
Object attrValue = attributes.get(attrName);
if(attrValue != null)
addAttribute(attrName, attrValue.toString());
}
} | java | {
"resource": ""
} |
q169029 | URLResource.extractInfo | validation | public static ResourceInfo extractInfo(URL url) throws IOException
{
URLConnection urlConnection = url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setUseCaches(false);
urlConnection.connect();
InputStream is = urlConnection.getInputStream();
try
{
return new StaticInfo(urlConnection.getContentLength(), urlConnection.getLastModified());
}
finally
{
is.close();
}
} | java | {
"resource": ""
} |
q169030 | AbstractResourceProvider.chroot | validation | @Override
public InternalResource chroot(InternalResource resource)
{
String path = resource.getPath();
// when it is a directory, we simply use the provided resource
if(resource.isDirectory())
{
return doCreateResourceProvider(path).getRootResource();
}
else
{
// when not a directory, we do a chroot to the parent and then we return the resource
// that points to it
return (InternalResource) resource.chroot("..").createRelative(resource.getFilename());
}
} | java | {
"resource": ""
} |
q169031 | AbstractResourceProvider.list | validation | @Override
public InternalResource[] list(InternalResource resource, final ResourceFilter filter)
throws IOException
{
final List<Resource> resources = new ArrayList<Resource>();
String path = PathUtils.addTrailingSlash(resource.getPath());
if(doList(path, new ResourceFilter()
{
@Override
public boolean accept(Resource resource)
{
boolean res = filter.accept(resource);
if(res)
resources.add(resource);
return res;
}
}))
{
return resources.toArray(new InternalResource[resources.size()]);
}
else
return null;
} | java | {
"resource": ""
} |
q169032 | AbstractResource.chroot | validation | @Override
public Resource chroot(String relativePath)
{
return _resourceProvider.chroot((InternalResource) createRelative(relativePath));
} | java | {
"resource": ""
} |
q169033 | FileResource.create | validation | public static Resource create(File file)
{
try
{
String path = file.getCanonicalPath();
if(file.isDirectory())
path = PathUtils.addTrailingSlash(path);
return create(new File("/"), path);
}
catch(IOException e)
{
throw new IllegalArgumentException("invalid file " + file, e);
}
} | java | {
"resource": ""
} |
q169034 | ExternalCommand.start | validation | public void start() throws IOException
{
_process = _processBuilder.start();
_out = new InputReader(new BufferedInputStream(_process.getInputStream()));
_err = new InputReader(new BufferedInputStream(_process.getErrorStream()));
_out.start();
_err.start();
} | java | {
"resource": ""
} |
q169035 | ExternalCommand.create | validation | public static ExternalCommand create(List<String> commands)
{
ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands));
return ec;
} | java | {
"resource": ""
} |
q169036 | ExternalCommand.start | validation | public static ExternalCommand start(String... commands) throws IOException
{
ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands));
ec.start();
return ec;
} | java | {
"resource": ""
} |
q169037 | ExternalCommand.execute | validation | public static ExternalCommand execute(File workingDirectory,
String command,
String... args)
throws IOException, InterruptedException
{
try
{
return executeWithTimeout(workingDirectory, command, 0, args);
}
catch (TimeoutException e)
{
// Can't happen!
throw new IllegalStateException(MODULE + ".execute: Unexpected timeout occurred!");
}
} | java | {
"resource": ""
} |
q169038 | Chronos.tick | validation | public long tick()
{
long tick = _clock.currentTimeMillis();
long diff = tick - _tick;
_tick = tick;
return diff;
} | java | {
"resource": ""
} |
q169039 | Chronos.getElapsedTime | validation | public String getElapsedTime()
{
StringBuilder sb = new StringBuilder("Time: ");
sb.append(this.tick());
sb.append(" ms");
return sb.toString();
} | java | {
"resource": ""
} |
q169040 | AbstractXMLBuilder.addTag | validation | @Override
public void addTag(String tagName,
int value,
String attrName,
String attrValue)
{
addTag(tagName, String.valueOf(value), attrName, attrValue);
} | java | {
"resource": ""
} |
q169041 | AbstractXMLBuilder.addTag | validation | @Override
public void addTag(String tagName, int value, Map attributes)
{
addTag(tagName, String.valueOf(value), attributes);
} | java | {
"resource": ""
} |
q169042 | Indent.indentBlock | validation | public static String indentBlock(String block, Indent indent)
{
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new StringReader(block));
String line;
try
{
while((line = br.readLine()) != null)
sb.append(indent).append(line).append('\n');
}
catch(IOException ex)
{
// on a String ? I doubt...
}
return sb.toString();
} | java | {
"resource": ""
} |
q169043 | ClockUtils.toEndTime | validation | public static long toEndTime(Clock clock, Object timeout)
{
Timespan t = toTimespan(timeout);
if(t == null)
return 0;
if(clock == null)
clock = SystemClock.INSTANCE;
if(t.getDurationInMilliseconds() == 0)
return 0;
return t.futureTimeMillis(clock);
} | java | {
"resource": ""
} |
q169044 | RAMDirectory.add | validation | public RAMEntry add(RAMEntry entry)
{
touch();
_directoryContent.put(entry.name(), entry);
return entry;
} | java | {
"resource": ""
} |
q169045 | RAMDirectory.mkdir | validation | public RAMDirectory mkdir(String name) throws IOException
{
RAMEntry entry = getEntry(name);
if(entry instanceof RAMDirectory)
{
RAMDirectory ramDirectory = (RAMDirectory) entry;
return ramDirectory;
}
else
{
if(entry == null)
{
RAMDirectory directory = new RAMDirectory(_clock, name);
return (RAMDirectory) add(directory);
}
else
{
throw new IOException("File exists: " + name);
}
}
} | java | {
"resource": ""
} |
q169046 | CodecUtils.encodeString | validation | public static String encodeString(OneWayCodec codec, String s)
{
try
{
return codec.encode(s.getBytes("UTF-8"));
}
catch(UnsupportedEncodingException ex)
{
// shouldn't happen
throw new RuntimeException(ex);
}
} | java | {
"resource": ""
} |
q169047 | CodecUtils.decodeString | validation | public static String decodeString(Codec codec, String s)
throws Codec.CannotDecodeException
{
try
{
return new String(codec.decode(s), "UTF-8");
}
catch(UnsupportedEncodingException ex)
{
// shouldn't happen
throw new RuntimeException(ex);
}
} | java | {
"resource": ""
} |
q169048 | LocalCacheLeafResource.create | validation | public static LeafResource create(Resource resource)
{
try
{
// if we can access the file then there is no reason to decorate it...
resource.getFile();
return new LeafResourceImpl(resource);
}
catch(IOException e)
{
return new LocalCacheLeafResource(resource);
}
} | java | {
"resource": ""
} |
q169049 | CollectionsUtils.reverse | validation | public static <T> T[] reverse(T[] array)
{
if(array == null)
return array;
int s = 0;
int e = array.length - 1;
while(s < e)
{
// swap index e and s
T tmp = array[e];
array[e] = array[s];
array[s] = tmp;
s++;
e--;
}
return array;
} | java | {
"resource": ""
} |
q169050 | CollectionsUtils.toEnumSet | validation | public static <T extends Enum<T>> EnumSet<T> toEnumSet(Class<T> clazz, T... ts)
{
if(ts == null)
return null;
EnumSet<T> res = EnumSet.noneOf(clazz);
for(T t : ts)
{
res.add(t);
}
return res;
} | java | {
"resource": ""
} |
q169051 | CollectionsUtils.loadProperties | validation | public static Properties loadProperties(File file) throws IOException
{
if(file == null)
return null;
FileReader reader = new FileReader(file);
try
{
return loadProperties(reader);
}
finally
{
reader.close();
}
} | java | {
"resource": ""
} |
q169052 | CollectionsUtils.loadProperties | validation | public static Properties loadProperties(Reader reader) throws IOException
{
if(reader == null)
return null;
Properties properties = new Properties();
properties.load(reader);
return properties;
} | java | {
"resource": ""
} |
q169053 | Timespan.getAsString | validation | public String getAsString(EnumSet<TimeUnit> timeUnits)
{
StringBuilder sb = new StringBuilder();
EnumMap<TimeUnit, Timespan> canonicalTimespans = getAsTimespans(timeUnits);
for(TimeUnit timeUnit : TIME_UNIT_ORDER)
{
if(canonicalTimespans.containsKey(timeUnit))
{
long duration = canonicalTimespans.get(timeUnit).getDuration();
if(duration > 0)
{
sb.append(duration).append(timeUnit.getDisplayChar());
}
}
}
if(sb.length() == 0)
{
sb.append(0);
if(timeUnits.contains(getTimeUnit()))
sb.append(getTimeUnit().getDisplayChar());
}
return sb.toString();
} | java | {
"resource": ""
} |
q169054 | Timespan.compareTo | validation | @Override
public int compareTo(Timespan timespan)
{
if(timespan.getTimeUnit() == getTimeUnit())
return LangUtils.compare(getDuration(), timespan.getDuration());
else
return LangUtils.compare(getDurationInMilliseconds(), timespan.getDurationInMilliseconds());
} | java | {
"resource": ""
} |
q169055 | MemorySize.truncate | validation | public MemorySize truncate(SizeUnit sizeUnit)
{
if (getSizeUnit() == sizeUnit)
return this;
long sizeInBytes = getSizeInBytes();
if (sizeInBytes >= sizeUnit.getBytesCount())
{
return new MemorySize(sizeInBytes / sizeUnit.getBytesCount(), sizeUnit);
}
else
{
return ZERO_SIZES.get(sizeUnit);
}
} | java | {
"resource": ""
} |
q169056 | MemorySize.add | validation | public MemorySize add(MemorySize other)
{
if(other == null)
throw new NullPointerException();
if(getSizeUnit() == other.getSizeUnit())
return new MemorySize(getSize() + other.getSize(), getSizeUnit());
return new MemorySize(getSizeInBytes() + other.getSizeInBytes(),
SizeUnit.BYTE);
} | java | {
"resource": ""
} |
q169057 | MemorySize.compareTo | validation | @Override
public int compareTo(MemorySize memorySize)
{
// according to javadoc for interface Comparable<T>, a NullPointerException
// should be thrown when the object to be compared with is null
// http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo(T)
if (memorySize == null)
throw new NullPointerException();
if (getSizeUnit() == memorySize.getSizeUnit())
return LangUtils.compare(getSize(), memorySize.getSize());
return LangUtils.compare(getSizeInBytes(), memorySize.getSizeInBytes());
} | java | {
"resource": ""
} |
q169058 | MemorySize.create | validation | public static MemorySize create(MemorySize...memorySizes)
{
if(memorySizes == null)
return null;
if(memorySizes.length == 0)
return ZERO_BYTES;
MemorySize res = memorySizes[0];
for(int i = 1; i < memorySizes.length; i++)
{
MemorySize memorySize = memorySizes[i];
if(memorySize != null)
res = res.add(memorySize);
}
return res;
} | java | {
"resource": ""
} |
q169059 | ThreadPerTaskExecutor.execute | validation | public static <V> Future<V> execute(Callable<V> callable)
{
FutureTask<V> futureTask = new FutureTask<V>(callable);
new Thread(futureTask).start();
return futureTask;
} | java | {
"resource": ""
} |
q169060 | MarkerManager.addMarker | validation | public void addMarker(T marker) {
final MarkerOptions markerOptions = new MarkerOptions();
marker.setMarkerManager(this);
marker.prepareMarker(markerOptions);
markerCache.put(marker, googleMap.addMarker(markerOptions));
marker.onAdd();
} | java | {
"resource": ""
} |
q169061 | MarkerManager.removeMarker | validation | public void removeMarker(T marker) {
final Marker realMarker = markerCache.get(marker);
if (realMarker != null) {
realMarker.remove();
}
markerCache.remove(marker);
} | java | {
"resource": ""
} |
q169062 | BitmapGenerator.fromView | validation | public static BitmapDescriptor fromView(View view) {
// TODO: Single views have trouble with measure.
final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(spec, spec);
final int width = view.getMeasuredWidth();
final int height = view.getMeasuredHeight();
view.layout(0, 0, width, height);
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
} | java | {
"resource": ""
} |
q169063 | FileObservable.onlyRelatedTo | validation | private final static Func1<WatchEvent<?>, Boolean> onlyRelatedTo(final File file) {
return new Func1<WatchEvent<?>, Boolean>() {
@Override
public Boolean call(WatchEvent<?> event) {
final boolean ok;
if (file.isDirectory())
ok = true;
else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind()))
ok = true;
else {
Object context = event.context();
if (context != null && context instanceof Path) {
Path p = (Path) context;
Path basePath = getBasePath(file);
File pFile = new File(basePath.toFile(), p.toString());
ok = pFile.getAbsolutePath().equals(file.getAbsolutePath());
} else
ok = false;
}
return ok;
}
};
} | java | {
"resource": ""
} |
q169064 | OnSubscribeWatchServiceEvents.emitEvents | validation | private static boolean emitEvents(WatchService watchService,
Subscriber<? super WatchEvent<?>> subscriber, long pollDurationMs,
long pollIntervalMs) {
// get the first event
WatchKey key = nextKey(watchService, subscriber, pollDurationMs);
if (key != null) {
if (subscriber.isUnsubscribed())
return false;
// we have a polled event, now we traverse it and
// receive all the states from it
for (WatchEvent<?> event : key.pollEvents()) {
if (subscriber.isUnsubscribed())
return false;
else
subscriber.onNext(event);
}
boolean valid = key.reset();
if (!valid && !subscriber.isUnsubscribed()) {
subscriber.onCompleted();
return false;
} else if (!valid)
return false;
}
return true;
} | java | {
"resource": ""
} |
q169065 | ViewPagerIndicator.getSelectorDrawable | validation | private StateListDrawable getSelectorDrawable() {
StateListDrawable d = null;
try {
d = new StateListDrawable();
ShapeDrawable selectedDrawable = new ShapeDrawable(new OvalShape());
selectedDrawable.getPaint().setColor(mItemSelectedColor);
selectedDrawable.setIntrinsicHeight(mItemRadius * 2);
selectedDrawable.setIntrinsicWidth(mItemRadius * 2);
ShapeDrawable unselectedDrawable = new ShapeDrawable(new OvalShape());
unselectedDrawable.getPaint().setColor(mItemUnselectedColor);
unselectedDrawable.setIntrinsicHeight(mItemRadius * 2);
unselectedDrawable.setIntrinsicWidth(mItemRadius * 2);
d.addState(new int[]{android.R.attr.state_checked}, selectedDrawable);
d.addState(new int[]{}, unselectedDrawable);
} catch(Exception e) {
Log.e(TAG, getMessageFor(e));
}
return d;
} | java | {
"resource": ""
} |
q169066 | ViewPagerIndicator.initWithViewPager | validation | public void initWithViewPager(ViewPager viewPager) throws IllegalStateException {
if ( viewPager == null ) return;
if ( viewPager.getAdapter() == null ) throw new IllegalStateException("ViewPager has no adapter set.");
try {
mViewPager = viewPager;
mViewPager.addOnPageChangeListener(mOnPageChangeListener);
addViews();
} catch(Exception e) {
Log.e(TAG, getMessageFor(e));
}
} | java | {
"resource": ""
} |
q169067 | ViewPagerIndicator.addViews | validation | private void addViews() {
try {
if ( mViewPager == null || mViewPager.getAdapter() == null || mViewPager.getAdapter().getCount() == 0 ) return;
removeAllViews();
AppCompatRadioButton firstItem = new AppCompatRadioButton(getContext());
firstItem.setText("");
firstItem.setButtonDrawable(mButtonDrawable.getConstantState().newDrawable());
ViewPagerIndicator.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
firstItem.setLayoutParams(params);
firstItem.setClickable(false);
addView(firstItem);
for ( int i=1; i<mViewPager.getAdapter().getCount(); i++ ) {
AppCompatRadioButton item = new AppCompatRadioButton(getContext());
item.setText("");
item.setButtonDrawable(mButtonDrawable.getConstantState().newDrawable());
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(mItemDividerWidth, 0, 0, 0);
item.setLayoutParams(params);
item.setClickable(false);
addView(item);
}
check(firstItem.getId());
} catch(Exception e) {
Log.e(TAG, getMessageFor(e));
}
} | java | {
"resource": ""
} |
q169068 | ViewPagerIndicator.getMessageFor | validation | private String getMessageFor(Exception e) {
if ( e == null ) return TAG + ": No Message.";
return e != null && e.getMessage() != null ? e.getMessage() : e.getClass().getName() + ": No Message.";
} | java | {
"resource": ""
} |
q169069 | UUID.useSequentialIds | validation | public static void useSequentialIds() {
if (!sequential) {
// get string that changes every 10 minutes
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
df.setTimeZone(tz);
String date = df.format(new Date()).substring(0, 11);
// run an md5 hash of the string, no reason this needs to be secure
byte[] digest;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
digest = md.digest(date.getBytes("UTF-8"));
}
catch (Exception e) {
throw new RuntimeException("Could not create hash of date for the sequential counter", e);
}
// create integer from first 4 bytes of md5 hash
int x;
x = ((int)digest[0] & 0xFF);
x |= ((int)digest[1] & 0xFF) << 8;
x |= ((int)digest[2] & 0xFF) << 16;
x |= ((int)digest[3] & 0xFF) << 24;
COUNTER.set(x);
}
sequential = true;
} | java | {
"resource": ""
} |
q169070 | UUID.intValue | validation | private static int intValue(char x) {
if (x >= '0' && x <= '9')
return x - '0';
if (x >= 'a' && x <= 'f')
return x - 'a' + 10;
if (x >= 'A' && x <= 'F')
return x - 'A' + 10;
throw new RuntimeException("Error parsing UUID at character: " + x);
} | java | {
"resource": ""
} |
q169071 | UUID.mapToByte | validation | private static byte mapToByte(char a, char b) {
int ai = intValue(a);
int bi = intValue(b);
return (byte) ((ai << 4) | bi);
} | java | {
"resource": ""
} |
q169072 | UUID.getTimestamp | validation | public Date getTimestamp() {
if (getVersion() != VERSION)
return null;
long time;
time = ((long)content[10] & 0xFF) << 40;
time |= ((long)content[11] & 0xFF) << 32;
time |= ((long)content[12] & 0xFF) << 24;
time |= ((long)content[13] & 0xFF) << 16;
time |= ((long)content[14] & 0xFF) << 8;
time |= ((long)content[15] & 0xFF);
return new Date(time);
} | java | {
"resource": ""
} |
q169073 | UUID.getMacFragment | validation | public byte[] getMacFragment() {
if (getVersion() != 'b')
return null;
byte[] x = new byte[6];
x[0] = 0;
x[1] = 0;
x[2] = (byte) (content[6] & 0xF);
x[3] = content[7];
x[4] = content[8];
x[5] = content[9];
return x;
} | java | {
"resource": ""
} |
q169074 | SocializeConfig.setProperty | validation | public void setProperty(String key, String value) {
if(properties == null) {
properties = createProperties();
}
if(value != null) {
value = value.trim();
properties.put(key, value);
}
else {
properties.remove(key);
}
} | java | {
"resource": ""
} |
q169075 | SocializeConfig.setFacebookUserCredentials | validation | @Deprecated
public void setFacebookUserCredentials(String userId, String token) {
setProperty(SocializeConfig.FACEBOOK_USER_ID, userId);
setProperty(SocializeConfig.FACEBOOK_USER_TOKEN, token);
} | java | {
"resource": ""
} |
q169076 | SocializeConfig.setSocializeCredentials | validation | public void setSocializeCredentials(String consumerKey, String consumerSecret) {
setProperty(SocializeConfig.SOCIALIZE_CONSUMER_KEY, consumerKey);
setProperty(SocializeConfig.SOCIALIZE_CONSUMER_SECRET, consumerSecret);
} | java | {
"resource": ""
} |
q169077 | SocializeConfig.merge | validation | public void merge(Properties other, Set<String> toBeRemoved) {
if(properties == null) {
properties = createProperties();
}
if(other != null && other.size() > 0) {
Set<Entry<Object, Object>> entrySet = other.entrySet();
for (Entry<Object, Object> entry : entrySet) {
properties.put(entry.getKey(), entry.getValue());
}
}
if(toBeRemoved != null && toBeRemoved.size() > 0) {
for (String key : toBeRemoved) {
properties.remove(key);
}
toBeRemoved.clear();
}
} | java | {
"resource": ""
} |
q169078 | SocializeShareUtils.doShare | validation | protected void doShare(final Activity context, final Entity entity, final ShareType shareType, final ShareAddListener shareAddListener) {
final SocializeSession session = getSocialize().getSession();
shareSystem.addShare(context, session, entity, "", shareType, null, new ShareAddListener() {
@Override
public void onError(SocializeException error) {
if(shareAddListener != null) {
shareAddListener.onError(error);
}
}
@Override
public void onCreate(Share share) {
if(share != null && shareSystem != null) {
handleNonNetworkShare(context, session, shareType, share, "", null, shareAddListener);
}
}
});
} | java | {
"resource": ""
} |
q169079 | SocializeShareUtils.handleNonNetworkShare | validation | protected void handleNonNetworkShare(Activity activity, final SocializeSession session, final ShareType shareType, final Share share, String shareText, Location location, final ShareAddListener shareAddListener) {
SocialNetworkListener snListener = new SocialNetworkListener() {
@Override
public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
if(shareAddListener != null) {
shareAddListener.onError(SocializeException.wrap(error));
}
}
@Override
public void onCancel() {
if(shareAddListener != null) {
shareAddListener.onCancel();
}
}
@Override
public boolean onBeforePost(Activity parent, SocialNetwork socialNetwork, PostData postData) {
return shareAddListener instanceof SocialNetworkListener && ((SimpleShareListener) shareAddListener).onBeforePost(parent, socialNetwork, postData);
}
@Override
public void onAfterPost(Activity parent, SocialNetwork socialNetwork, JSONObject responseObject) {
if(shareAddListener != null) {
shareAddListener.onCreate(share);
}
}
};
shareSystem.share(activity, session, share, shareText, location, shareType, snListener);
} | java | {
"resource": ""
} |
q169080 | CommentUtils.addComment | validation | public static void addComment (Activity context, Entity entity, String text, CommentAddListener listener) {
proxy.addComment(context, entity, text, listener);
} | java | {
"resource": ""
} |
q169081 | CommentUtils.deleteComment | validation | public static void deleteComment (Activity context, long id, CommentDeleteListener listener) {
proxy.deleteComment(context, id, listener);
} | java | {
"resource": ""
} |
q169082 | CommentUtils.addComment | validation | public static void addComment (Activity context, Entity entity, String text, CommentOptions commentOptions, CommentAddListener listener, SocialNetwork...networks) {
proxy.addComment(context, entity, text, commentOptions, listener, networks);
} | java | {
"resource": ""
} |
q169083 | CommentUtils.getComment | validation | public static void getComment (Activity context, CommentGetListener listener, long id) {
proxy.getComment(context, id, listener);
} | java | {
"resource": ""
} |
q169084 | CommentUtils.getComments | validation | public static void getComments (Activity context, CommentListListener listener, long...ids) {
proxy.getComments(context, listener, ids);
} | java | {
"resource": ""
} |
q169085 | CommentUtils.getCommentsByUser | validation | public static void getCommentsByUser (Activity context, User user, int start, int end, CommentListListener listener) {
proxy.getCommentsByUser(context, user, start, end, listener);
} | java | {
"resource": ""
} |
q169086 | CommentUtils.getCommentsByEntity | validation | public static void getCommentsByEntity (Activity context, String entityKey, int start, int end, CommentListListener listener) {
proxy.getCommentsByEntity(context, entityKey, start, end, listener);
} | java | {
"resource": ""
} |
q169087 | CommentUtils.getCommentsByApplication | validation | public static void getCommentsByApplication (Activity context, int start, int end, CommentListListener listener) {
proxy.getCommentsByApplication(context, start, end, listener);
} | java | {
"resource": ""
} |
q169088 | CommentUtils.showCommentView | validation | public static void showCommentView(Activity context, Entity entity, OnCommentViewActionListener listener) {
proxy.showCommentView(context, entity, listener);
} | java | {
"resource": ""
} |
q169089 | JSONParser.parseObject | validation | public JSONObject parseObject(String json) throws JSONException {
json = json.trim();
if(json.startsWith("[")) {
JSONArray array = new JSONArray(json);
JSONObject obj = new JSONObject();
obj.put("data", array);
return obj;
}
else {
return new JSONObject(json);
}
} | java | {
"resource": ""
} |
q169090 | Util.openUrl | validation | public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Util.logd("Facebook-Util", method + " URL: " + url);
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
Object parameter = params.get(key);
if (parameter instanceof byte[]) {
dataparams.putByteArray(key, (byte[])parameter);
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
if (params.containsKey("access_token")) {
String decoded_token =
URLDecoder.decode(params.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type",
"multipart/form-data;boundary="+strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(("--" + strBoundary +endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key: dataparams.keySet()){
os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine).getBytes());
}
}
os.flush();
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
public static void clearCookies(Context context) {
// Edge case: an illegal state exception is thrown if an instance of
// CookieSyncManager has not be created. CookieSyncManager is normally
// created by a WebKit view, but this might happen if you start the
// app, restore saved state, and click logout before running a UI
// dialog in a WebView -- in which case the app crashes
@SuppressWarnings("unused")
CookieSyncManager cookieSyncMngr =
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
} | java | {
"resource": ""
} |
q169091 | Util.parseJson | validation | public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
} | java | {
"resource": ""
} |
q169092 | Util.showAlert | validation | public static void showAlert(Context context, String title, String text) {
Builder alertBuilder = new Builder(context);
alertBuilder.setTitle(title);
alertBuilder.setMessage(text);
alertBuilder.create().show();
} | java | {
"resource": ""
} |
q169093 | Util.logd | validation | public static void logd(String tag, String msg) {
if (ENABLE_LOG) {
Log.d(tag, msg);
}
} | java | {
"resource": ""
} |
q169094 | TypeAdapterRuntimeTypeWrapper.getRuntimeTypeIfMoreSpecific | validation | private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
if (value != null
&& (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
type = value.getClass();
}
return type;
} | java | {
"resource": ""
} |
q169095 | SocializeAction.setEntitySafe | validation | public void setEntitySafe(Entity entity) {
if(StringUtils.isEmpty(entity.getName())) {
setEntityKey(entity.getKey());
}
else {
setEntity(entity);
}
} | java | {
"resource": ""
} |
q169096 | FacebookUrlBuilder.buildProfileImageUrl | validation | public String buildProfileImageUrl(String id) {
StringBuilder builder = new StringBuilder();
builder.append("http://graph.facebook.com/");
builder.append(id);
builder.append("/picture?type=large");
return builder.toString();
} | java | {
"resource": ""
} |
q169097 | ProfileLayoutView.onImageChange | validation | public void onImageChange(Bitmap bitmap) {
if(bitmap != null) {
Bitmap scaled = bitmapUtils.getScaledBitmap(bitmap, 200, 200);
content.onProfilePictureChange(scaled);
}
} | java | {
"resource": ""
} |
q169098 | SignatureBaseString.generate | validation | public String generate() throws OAuthMessageSignerException {
try {
String normalizedUrl = normalizeRequestUrl();
String normalizedParams = normalizeRequestParameters();
return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&'
+ OAuth.percentEncode(normalizedParams);
} catch (Exception e) {
throw new OAuthMessageSignerException(e);
}
} | java | {
"resource": ""
} |
q169099 | SignatureBaseString.normalizeRequestParameters | validation | public String normalizeRequestParameters() throws IOException {
if (requestParameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<String> iter = requestParameters.keySet().iterator();
for (int i = 0; iter.hasNext(); i++) {
String param = iter.next();
if (OAuth.OAUTH_SIGNATURE.equals(param) || "realm".equals(param)) {
continue;
}
if (i > 0) {
sb.append("&");
}
sb.append(requestParameters.getAsQueryString(param));
}
return sb.toString();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.