_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q20000 | JavacFileManager.listArchive | train | private void listArchive(Archive archive,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) {
// Get the files directly in the subdir
List<String> files = archive.getFiles(subdirectory);
if (files != null) {
for (; !files.isEmpty(); files = files.tail) {
String file = files.head;
if (isValidFile(file, fileKinds)) {
resultList.append(archive.getFileObject(subdirectory, file));
}
}
}
if (recurse) {
for (RelativeDirectory s: archive.getSubdirectories()) {
if (subdirectory.contains(s)) {
// Because the archive map is a flat list of directories,
// the enclosing loop will pick up all child subdirectories.
// Therefore, there is no need to recurse deeper.
listArchive(archive, s, fileKinds, false, resultList);
}
}
}
} | java | {
"resource": ""
} |
q20001 | JavacFileManager.listContainer | train | private void listContainer(File container,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) {
Archive archive = archives.get(container);
if (archive == null) {
// archives are not created for directories.
if (fsInfo.isDirectory(container)) {
listDirectory(container,
subdirectory,
fileKinds,
recurse,
resultList);
return;
}
// Not a directory; either a file or non-existant, create the archive
try {
archive = openArchive(container);
} catch (IOException ex) {
log.error("error.reading.file",
container, getMessage(ex));
return;
}
}
listArchive(archive,
subdirectory,
fileKinds,
recurse,
resultList);
} | java | {
"resource": ""
} |
q20002 | JavacFileManager.openArchive | train | private Archive openArchive(File zipFileName, boolean useOptimizedZip) throws IOException {
File origZipFileName = zipFileName;
if (symbolFileEnabled && locations.isDefaultBootClassPathRtJar(zipFileName)) {
File file = zipFileName.getParentFile().getParentFile(); // ${java.home}
if (new File(file.getName()).equals(new File("jre")))
file = file.getParentFile();
// file == ${jdk.home}
for (String name : symbolFileLocation)
file = new File(file, name);
// file == ${jdk.home}/lib/ct.sym
if (file.exists())
zipFileName = file;
}
Archive archive;
try {
ZipFile zdir = null;
boolean usePreindexedCache = false;
String preindexCacheLocation = null;
if (!useOptimizedZip) {
zdir = new ZipFile(zipFileName);
} else {
usePreindexedCache = options.isSet("usezipindex");
preindexCacheLocation = options.get("java.io.tmpdir");
String optCacheLoc = options.get("cachezipindexdir");
if (optCacheLoc != null && optCacheLoc.length() != 0) {
if (optCacheLoc.startsWith("\"")) {
if (optCacheLoc.endsWith("\"")) {
optCacheLoc = optCacheLoc.substring(1, optCacheLoc.length() - 1);
}
else {
optCacheLoc = optCacheLoc.substring(1);
}
}
File cacheDir = new File(optCacheLoc);
if (cacheDir.exists() && cacheDir.canWrite()) {
preindexCacheLocation = optCacheLoc;
if (!preindexCacheLocation.endsWith("/") &&
!preindexCacheLocation.endsWith(File.separator)) {
preindexCacheLocation += File.separator;
}
}
}
}
if (origZipFileName == zipFileName) {
if (!useOptimizedZip) {
archive = new ZipArchive(this, zdir);
} else {
archive = new ZipFileIndexArchive(this,
zipFileIndexCache.getZipFileIndex(zipFileName,
null,
usePreindexedCache,
preindexCacheLocation,
options.isSet("writezipindexfiles")));
}
} else {
if (!useOptimizedZip) {
archive = new SymbolArchive(this, origZipFileName, zdir, symbolFilePrefix);
} else {
archive = new ZipFileIndexArchive(this,
zipFileIndexCache.getZipFileIndex(zipFileName,
symbolFilePrefix,
usePreindexedCache,
preindexCacheLocation,
options.isSet("writezipindexfiles")));
}
}
} catch (FileNotFoundException ex) {
archive = new MissingArchive(zipFileName);
} catch (ZipFileIndex.ZipFormatException zfe) {
throw zfe;
} catch (IOException ex) {
if (zipFileName.exists())
log.error("error.reading.file", zipFileName, getMessage(ex));
archive = new MissingArchive(zipFileName);
}
archives.put(origZipFileName, archive);
return archive;
} | java | {
"resource": ""
} |
q20003 | KeyTransactionCache.add | train | public void add(Collection<KeyTransaction> keyTransactions)
{
for(KeyTransaction keyTransaction : keyTransactions)
this.keyTransactions.put(keyTransaction.getId(), keyTransaction);
} | java | {
"resource": ""
} |
q20004 | VATINStructureManager.getFromValidVATIN | train | @Nullable
public static VATINStructure getFromValidVATIN (@Nullable final String sVATIN)
{
if (StringHelper.getLength (sVATIN) > 2)
for (final VATINStructure aStructure : s_aList)
if (aStructure.isValid (sVATIN))
return aStructure;
return null;
} | java | {
"resource": ""
} |
q20005 | VATINStructureManager.getFromVATINCountry | train | @Nullable
public static VATINStructure getFromVATINCountry (@Nullable final String sVATIN)
{
if (StringHelper.getLength (sVATIN) >= 2)
{
final String sCountry = sVATIN.substring (0, 2);
for (final VATINStructure aStructure : s_aList)
if (aStructure.getExamples ().get (0).substring (0, 2).equalsIgnoreCase (sCountry))
return aStructure;
}
return null;
} | java | {
"resource": ""
} |
q20006 | WrappingJavaFileManager.wrap | train | protected Iterable<JavaFileObject> wrap(Iterable<JavaFileObject> fileObjects) {
List<JavaFileObject> mapped = new ArrayList<JavaFileObject>();
for (JavaFileObject fileObject : fileObjects)
mapped.add(wrap(fileObject));
return Collections.unmodifiableList(mapped);
} | java | {
"resource": ""
} |
q20007 | ControlFactory.createInstance | train | public static Control createInstance(ControlVersion version)
{
switch (version)
{
case _0_24:
return new Control0_24();
case _0_25:
return new Control0_25();
default:
throw new IllegalArgumentException("Unknown control version: " + version);
}
} | java | {
"resource": ""
} |
q20008 | Widget.attach | train | protected final void attach(Attachable widget) {
if (user != null) {
widget.addTo(user);
} else {
if (waitingForUser == null) waitingForUser = new LinkedList<Attachable>();
waitingForUser.add(widget);
}
} | java | {
"resource": ""
} |
q20009 | ClassServiceUtility.getClassFinder | train | public org.jbundle.util.osgi.ClassFinder getClassFinder(Object context)
{
if (!classServiceAvailable)
return null;
try {
if (classFinder == null)
{
Class.forName("org.osgi.framework.BundleActivator"); // This tests to see if osgi exists
//classFinder = (org.jbundle.util.osgi.ClassFinder)org.jbundle.util.osgi.finder.ClassFinderActivator.getClassFinder(context, -1);
try { // Use reflection so the smart jvm's don't try to retrieve this class.
Class<?> clazz = Class.forName("org.jbundle.util.osgi.finder.ClassFinderActivator"); // This tests to see if osgi exists
if (clazz != null)
{
java.lang.reflect.Method method = clazz.getMethod("getClassFinder", Object.class, int.class);
if (method != null)
classFinder = (org.jbundle.util.osgi.ClassFinder)method.invoke(null, context, -1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return classFinder;
} catch (ClassNotFoundException ex) {
classServiceAvailable = false; // Osgi is not installed, no need to keep trying
return null;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q20010 | ClassServiceUtility.getResourceBundle | train | public final ResourceBundle getResourceBundle(String className, Locale locale, String version, ClassLoader classLoader) throws MissingResourceException
{
MissingResourceException ex = null;
ResourceBundle resourceBundle = null;
try {
resourceBundle = ResourceBundle.getBundle(className, locale);
} catch (MissingResourceException e) {
ex = e;
}
if (resourceBundle == null)
{
try {
if (this.getClassFinder(null) != null)
resourceBundle = this.getClassFinder(null).findResourceBundle(className, locale, version); // Try to find this class in the obr repos
} catch (MissingResourceException e) {
ex = e;
}
}
if (resourceBundle == null)
if (ex != null)
throw ex;
return resourceBundle;
} | java | {
"resource": ""
} |
q20011 | ClassServiceUtility.getFullClassName | train | public static String getFullClassName(String packageName, String className) {
return ClassServiceUtility.getFullClassName(null, packageName, className);
} | java | {
"resource": ""
} |
q20012 | DataBinder.find | train | public String find(String name) {
String value = null;
for (DataBinder top = this; top != null && (value = top.get(name)) == null; top = top.getLower());
return value;
} | java | {
"resource": ""
} |
q20013 | DataBinder.put | train | public String put(String name, String value, String alternative) {
return put(name, value != null ? value : alternative);
} | java | {
"resource": ""
} |
q20014 | DataBinder.putResultSet | train | public CachedResultSet putResultSet(String name, CachedResultSet rs) {
return _rsets.put(name, rs);
} | java | {
"resource": ""
} |
q20015 | DataBinder.putNamedObject | train | @SuppressWarnings("unchecked")
public <T, V> T putNamedObject(String name, V object) {
return (T)_named.put(name, object);
} | java | {
"resource": ""
} |
q20016 | DataBinder.getNamedObject | train | @SuppressWarnings("unchecked")
public <T> T getNamedObject(String name) {
return (T)_named.get(name);
} | java | {
"resource": ""
} |
q20017 | DataBinder.getNamedObject | train | public <T> T getNamedObject(String name, Class<T> type) {
return type.cast(_named.get(name));
} | java | {
"resource": ""
} |
q20018 | DataBinder.map | train | public <K, V> Map<K, V> map(String name, Class<K> ktype, Class<V> vtype) {
Map<K, V> map = getNamedObject(name);
if (map == null) putNamedObject(name, map = new HashMap<K, V>());
return map;
} | java | {
"resource": ""
} |
q20019 | DataBinder.mul | train | public <K, V> Multimap<K, V> mul(String name, Class<K> ktype, Class<V> vtype) {
Multimap<K, V> map = getNamedObject(name);
if (map == null) putNamedObject(name, map = new Multimap<K, V>());
return map;
} | java | {
"resource": ""
} |
q20020 | DataBinder.process | train | @Override
public DataBinder process(ResultSet rset) throws Exception {
try {
if (rset.next()) {
ResultSetMetaData meta = rset.getMetaData();
int width = meta.getColumnCount();
for (int i = 1; i <= width; ++i) {
Object value = rset.getObject(i);
if (value != null) {
put(Strings.toLowerCamelCase(meta.getColumnLabel(i), '_'), value.toString());
}
}
} else {
throw new NoSuchElementException("NoSuchRow");
}
return this;
} finally {
rset.close();
}
} | java | {
"resource": ""
} |
q20021 | DataBinder.put | train | public DataBinder put(Object object) throws Exception {
for (Field field: Beans.getKnownInstanceFields(object.getClass())) {
Object value = field.get(object);
if (value != null) {
put(field.getName(), value.toString());
}
}
return this;
} | java | {
"resource": ""
} |
q20022 | DataBinder.put | train | public <T extends DataObject> DataBinder put(T object, String... names) throws Exception {
Class<?> type = object.getClass();
Object value;
for (String name: names) {
Field field = Beans.getKnownField(type, name);
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers()) && (value = field.get(object)) != null) {
put(field.getName(), value.toString());
}
}
return this;
} | java | {
"resource": ""
} |
q20023 | DataBinder.load | train | public DataBinder load(String[] args, int offset) {
for (int i = offset; i < args.length; ++i) {
int equal = args[i].indexOf('=');
if (equal > 0) {
put(args[i].substring(0, equal), args[i].substring(equal + 1));
} else {
throw new RuntimeException("***InvalidParameter{" + args[i] + '}');
}
}
return this;
} | java | {
"resource": ""
} |
q20024 | DataBinder.load | train | public DataBinder load(String filename) throws IOException {
Properties props = new Properties();
Reader reader = new FileReader(filename);
props.load(reader);
reader.close();
return load(props);
} | java | {
"resource": ""
} |
q20025 | DataBinder.load | train | public DataBinder load(Properties props) {
Enumeration<?> enumeration = props.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String)enumeration.nextElement();
put(key, props.getProperty(key));
}
return this;
} | java | {
"resource": ""
} |
q20026 | DataBinder.estimateMaximumBytes | train | public int estimateMaximumBytes() {
int count = this.size();
for (String key: _rsets.keySet()) {
CachedResultSet crs = _rsets.get(key);
if (crs.rows != null) {
count += crs.columns.length*crs.rows.size();
}
}
return count * 64;
} | java | {
"resource": ""
} |
q20027 | DataBinder.toJSON | train | public String toJSON() {
JSONBuilder jb = new JSONBuilder(estimateMaximumBytes()).append('{');
appendParams(jb).append(',');
appendTables(jb);
jb.append('}');
return jb.toString();
} | java | {
"resource": ""
} |
q20028 | DateUtilities.getDateForHour | train | private static long getDateForHour(long dt, TimeZone tz, int hour, int dayoffset)
{
Calendar c = getCalendar(tz);
c.setTimeInMillis(dt);
int dd = c.get(Calendar.DAY_OF_MONTH);
int mm = c.get(Calendar.MONTH);
int yy = c.get(Calendar.YEAR);
c.set(yy, mm, dd, hour, 0, 0);
c.set(Calendar.MILLISECOND, 0);
if(dayoffset != 0)
c.add(Calendar.DAY_OF_MONTH, dayoffset);
return c.getTimeInMillis();
} | java | {
"resource": ""
} |
q20029 | DateUtilities.getCalendar | train | public static Calendar getCalendar(TimeZone tz, Locale locale)
{
if(tz == null)
tz = getCurrentTimeZone();
if(locale == null)
locale = getCurrentLocale();
return Calendar.getInstance(tz, locale);
} | java | {
"resource": ""
} |
q20030 | DateUtilities.getLocale | train | public static Locale getLocale(String country)
{
if(country == null || country.length() == 0)
country = Locale.getDefault().getCountry();
List<Locale> locales = LocaleUtils.languagesByCountry(country);
Locale locale = Locale.getDefault();
if(locales.size() > 0)
locale = locales.get(0); // Use the first locale that matches the country
return locale;
} | java | {
"resource": ""
} |
q20031 | DateUtilities.setCalendarData | train | public static void setCalendarData(Calendar calendar, Locale locale)
{
int[] array = (int[])localeData.get(locale);
if(array == null)
{
Calendar c = Calendar.getInstance(locale);
array = new int[2];
array[0] = c.getFirstDayOfWeek();
array[1] = c.getMinimalDaysInFirstWeek();
localeData.putIfAbsent(locale, array);
}
calendar.setFirstDayOfWeek(array[0]);
calendar.setMinimalDaysInFirstWeek(array[1]);
} | java | {
"resource": ""
} |
q20032 | DateUtilities.addDays | train | public static Date addDays(long dt, int days)
{
Calendar c = getCalendar();
if(dt > 0L)
c.setTimeInMillis(dt);
c.add(Calendar.DATE, days);
return c.getTime();
} | java | {
"resource": ""
} |
q20033 | DateUtilities.convertToUtc | train | public static long convertToUtc(long millis, String tz)
{
long ret = millis;
if(tz != null && tz.length() > 0)
{
DateTime dt = new DateTime(millis, DateTimeZone.forID(tz));
ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis();
}
return ret;
} | java | {
"resource": ""
} |
q20034 | JavacServer.useServer | train | public static int useServer(String settings, String[] args,
Set<URI> sourcesToCompile,
Set<URI> visibleSources,
Map<URI, Set<String>> visibleClasses,
Map<String, Set<URI>> packageArtifacts,
Map<String, Set<String>> packageDependencies,
Map<String, String> packagePubapis,
SysInfo sysinfo,
PrintStream out,
PrintStream err) {
try {
// The id can perhaps be used in the future by the javac server to reuse the
// JavaCompiler instance for several compiles using the same id.
String id = Util.extractStringOption("id", settings);
String portfile = Util.extractStringOption("portfile", settings);
String logfile = Util.extractStringOption("logfile", settings);
String stdouterrfile = Util.extractStringOption("stdouterrfile", settings);
String background = Util.extractStringOption("background", settings);
if (background == null || !background.equals("false")) {
background = "true";
}
// The sjavac option specifies how the server part of sjavac is spawned.
// If you have the experimental sjavac in your path, you are done. If not, you have
// to point to a com.sun.tools.sjavac.Main that supports --startserver
// for example by setting: sjavac=java%20-jar%20...javac.jar%com.sun.tools.sjavac.Main
String sjavac = Util.extractStringOption("sjavac", settings);
int poolsize = Util.extractIntOption("poolsize", settings);
int keepalive = Util.extractIntOption("keepalive", settings);
if (keepalive <= 0) {
// Default keepalive for server is 120 seconds.
// I.e. it will accept 120 seconds of inactivity before quitting.
keepalive = 120;
}
if (portfile == null) {
err.println("No portfile was specified!");
return -1;
}
if (logfile == null) {
logfile = portfile + ".javaclog";
}
if (stdouterrfile == null) {
stdouterrfile = portfile + ".stdouterr";
}
// Default to sjavac and hope it is in the path.
if (sjavac == null) {
sjavac = "sjavac";
}
int attempts = 0;
int rc = -1;
do {
PortFile port_file = getPortFile(portfile);
synchronized (port_file) {
port_file.lock();
port_file.getValues();
port_file.unlock();
}
if (!port_file.containsPortInfo()) {
String cmd = fork(sjavac, port_file.getFilename(), logfile, poolsize, keepalive, err, stdouterrfile, background);
if (background.equals("true") && !port_file.waitForValidValues()) {
// Ouch the server did not start! Lets print its stdouterrfile and the command used.
printFailedAttempt(cmd, stdouterrfile, err);
// And give up.
return -1;
}
}
rc = connectAndCompile(port_file, id, args, sourcesToCompile, visibleSources,
packageArtifacts, packageDependencies, packagePubapis, sysinfo,
out, err);
// Try again until we manage to connect. Any error after that
// will cause the compilation to fail.
if (rc == ERROR_BUT_TRY_AGAIN) {
// We could not connect to the server. Try again.
attempts++;
try {
Thread.sleep(WAIT_BETWEEN_CONNECT_ATTEMPTS);
} catch (InterruptedException e) {
}
}
} while (rc == ERROR_BUT_TRY_AGAIN && attempts < MAX_NUM_CONNECT_ATTEMPTS);
return rc;
} catch (Exception e) {
e.printStackTrace(err);
return -1;
}
} | java | {
"resource": ""
} |
q20035 | JavacServer.fork | train | private static String fork(String sjavac, String portfile, String logfile, int poolsize, int keepalive,
final PrintStream err, String stdouterrfile, String background)
throws IOException, ProblemException {
if (stdouterrfile != null && stdouterrfile.trim().equals("")) {
stdouterrfile = null;
}
final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive="+ keepalive;
if (background.equals("true")) {
sjavac += "%20" + startserver;
sjavac = sjavac.replaceAll("%20", " ");
sjavac = sjavac.replaceAll("%2C", ",");
// If the java/sh/cmd launcher fails the failure will be captured by stdouterr because of the redirection here.
String[] cmd = {"/bin/sh", "-c", sjavac + " >> " + stdouterrfile + " 2>&1"};
if (!(new File("/bin/sh")).canExecute()) {
ArrayList<String> wincmd = new ArrayList<String>();
wincmd.add("cmd");
wincmd.add("/c");
wincmd.add("start");
wincmd.add("cmd");
wincmd.add("/c");
wincmd.add(sjavac + " >> " + stdouterrfile + " 2>&1");
cmd = wincmd.toArray(new String[wincmd.size()]);
}
Process pp = null;
try {
pp = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace(err);
e.printStackTrace(new PrintWriter(stdouterrfile));
}
StringBuilder rs = new StringBuilder();
for (String s : cmd) {
rs.append(s + " ");
}
return rs.toString();
}
// Do not spawn a background server, instead run it within the same JVM.
Thread t = new Thread() {
@Override
public void run() {
try {
JavacServer.startServer(startserver, err);
} catch (Throwable t) {
t.printStackTrace(err);
}
}
};
t.start();
return "";
} | java | {
"resource": ""
} |
q20036 | JavacServer.connectGetSysInfo | train | public static SysInfo connectGetSysInfo(String serverSettings, PrintStream out, PrintStream err) {
SysInfo sysinfo = new SysInfo(-1, -1);
String id = Util.extractStringOption("id", serverSettings);
String portfile = Util.extractStringOption("portfile", serverSettings);
try {
PortFile pf = getPortFile(portfile);
useServer(serverSettings, new String[0],
new HashSet<URI>(),
new HashSet<URI>(),
new HashMap<URI, Set<String>>(),
new HashMap<String, Set<URI>>(),
new HashMap<String, Set<String>>(),
new HashMap<String, String>(),
sysinfo, out, err);
} catch (Exception e) {
e.printStackTrace(err);
}
return sysinfo;
} | java | {
"resource": ""
} |
q20037 | JavacServer.run | train | private void run(PortFile portFile, PrintStream err, int keepalive) {
boolean fileDeleted = false;
long timeSinceLastCompile;
try {
// Every 5 second (check_portfile_interval) we test if the portfile has disappeared => quit
// Or if the last request was finished more than 125 seconds ago => quit
// 125 = seconds_of_inactivity_before_shutdown+check_portfile_interval
serverSocket.setSoTimeout(CHECK_PORTFILE_INTERVAL*1000);
for (;;) {
try {
Socket s = serverSocket.accept();
CompilerThread ct = compilerPool.grabCompilerThread();
ct.setSocket(s);
compilerPool.execute(ct);
flushLog();
} catch (java.net.SocketTimeoutException e) {
if (compilerPool.numActiveRequests() > 0) {
// Never quit while there are active requests!
continue;
}
// If this is the timeout after the portfile
// has been deleted by us. Then we truly stop.
if (fileDeleted) {
log("Quitting because of "+(keepalive+CHECK_PORTFILE_INTERVAL)+" seconds of inactivity!");
break;
}
// Check if the portfile is still there.
if (!portFile.exists()) {
// Time to quit because the portfile was deleted by another
// process, probably by the makefile that is done building.
log("Quitting because portfile was deleted!");
flushLog();
break;
}
// Check if portfile.stop is still there.
if (portFile.markedForStop()) {
// Time to quit because another process touched the file
// server.port.stop to signal that the server should stop.
// This is necessary on some operating systems that lock
// the port file hard!
log("Quitting because a portfile.stop file was found!");
portFile.delete();
flushLog();
break;
}
// Does the portfile still point to me?
if (!portFile.stillMyValues()) {
// Time to quit because another build has started.
log("Quitting because portfile is now owned by another javac server!");
flushLog();
break;
}
// Check how long since the last request finished.
long diff = System.currentTimeMillis() - compilerPool.lastRequestFinished();
if (diff < keepalive * 1000) {
// Do not quit if we have waited less than 120 seconds.
continue;
}
// Ok, time to quit because of inactivity. Perhaps the build
// was killed and the portfile not cleaned up properly.
portFile.delete();
fileDeleted = true;
log("" + keepalive + " seconds of inactivity quitting in "
+ CHECK_PORTFILE_INTERVAL + " seconds!");
flushLog();
// Now we have a second 5 second grace
// period where javac remote requests
// that have loaded the data from the
// recently deleted portfile can connect
// and complete their requests.
}
}
} catch (Exception e) {
e.printStackTrace(err);
e.printStackTrace(theLog);
flushLog();
} finally {
compilerPool.shutdown();
}
long realTime = System.currentTimeMillis() - serverStart;
log("Shutting down.");
log("Total wall clock time " + realTime + "ms build time " + totalBuildTime + "ms");
flushLog();
} | java | {
"resource": ""
} |
q20038 | SocketConnection.writeValue | train | public <T extends Object> void writeValue(T value) throws IOException {
writeValue(value, (Class<T>) value.getClass());
} | java | {
"resource": ""
} |
q20039 | ThriftEnvelopeEvent.deserializeFromStream | train | private void deserializeFromStream(final InputStream in) throws IOException
{
final byte[] dateTimeBytes = new byte[8];
in.read(dateTimeBytes, 0, 8);
eventDateTime = new DateTime(ByteBuffer.wrap(dateTimeBytes).getLong(0));
final byte[] sizeGranularityInBytes = new byte[4];
in.read(sizeGranularityInBytes, 0, 4);
final byte[] granularityBytes = new byte[ByteBuffer.wrap(sizeGranularityInBytes).getInt(0)];
in.read(granularityBytes, 0, granularityBytes.length);
granularity = Granularity.valueOf(new String(granularityBytes, Charset.forName("UTF-8")));
thriftEnvelope = deserializer.deserialize(null);
} | java | {
"resource": ""
} |
q20040 | ApplicationInstanceCache.add | train | public void add(Collection<ApplicationInstance> applicationInstances)
{
for(ApplicationInstance applicationInstance : applicationInstances)
this.applicationInstances.put(applicationInstance.getId(), applicationInstance);
} | java | {
"resource": ""
} |
q20041 | DateFormatPool.get | train | public Object get()
{
synchronized(this)
{
if (freePool.isEmpty() || usedPool.size() >= capacity)
{
try
{
wait(1000);
}
catch (InterruptedException e)
{
}
// The timeout value was reached
if (freePool.isEmpty())
add(new SimpleDateFormat());
}
Object o = freePool.get(0);
freePool.remove(o);
usedPool.add(o);
return o;
}
} | java | {
"resource": ""
} |
q20042 | DateFormatPool.getFormat | train | public SimpleDateFormat getFormat(String format)
{
SimpleDateFormat f = (SimpleDateFormat)get();
f.applyPattern(format);
return f;
} | java | {
"resource": ""
} |
q20043 | DateFormatPool.release | train | public void release(Object o)
{
synchronized(this)
{
usedPool.remove(o);
freePool.add(o);
notify();
}
} | java | {
"resource": ""
} |
q20044 | ConfiguratorMojo.execute | train | public void execute() throws MojoExecutionException {
ClassLoader classloader;
try {
classloader= createClassLoader();
} catch (Exception e) {
throw new MojoExecutionException("could not create classloader from dependencies", e);
}
AbstractConfiguration[] configurations;
try {
configurations= ConfigurationGenerator.execute(generatedSourceDirectory, applicationDefinition, classloader, getSLF4JLogger());
} catch (Exception e) {
throw new MojoExecutionException("could not generate the configurator", e);
}
getPluginContext().put(GENERATED_CONFIGURATIONS_KEY, configurations);
project.addCompileSourceRoot(generatedSourceDirectory.getPath());
} | java | {
"resource": ""
} |
q20045 | Rect.toShortString | train | public String toShortString(StringBuilder sb) {
sb.setLength(0);
sb.append('[');
sb.append(left);
sb.append(',');
sb.append(top);
sb.append("][");
sb.append(right);
sb.append(',');
sb.append(bottom);
sb.append(']');
return sb.toString();
} | java | {
"resource": ""
} |
q20046 | Rect.flattenToString | train | public String flattenToString() {
StringBuilder sb = new StringBuilder(32);
// WARNING: Do not change the format of this string, it must be
// preserved because Rects are saved in this flattened format.
sb.append(left);
sb.append(' ');
sb.append(top);
sb.append(' ');
sb.append(right);
sb.append(' ');
sb.append(bottom);
return sb.toString();
} | java | {
"resource": ""
} |
q20047 | Rect.set | train | public void set(Rect src) {
this.left = src.left;
this.top = src.top;
this.right = src.right;
this.bottom = src.bottom;
} | java | {
"resource": ""
} |
q20048 | Rect.offset | train | public void offset(int dx, int dy) {
left += dx;
top += dy;
right += dx;
bottom += dy;
} | java | {
"resource": ""
} |
q20049 | Rect.contains | train | public boolean contains(int left, int top, int right, int bottom) {
// check for empty first
return this.left < this.right && this.top < this.bottom
// now check for containment
&& this.left <= left && this.top <= top
&& this.right >= right && this.bottom >= bottom;
} | java | {
"resource": ""
} |
q20050 | Rect.contains | train | public boolean contains(Rect r) {
// check for empty first
return this.left < this.right && this.top < this.bottom
// now check for containment
&& left <= r.left && top <= r.top && right >= r.right && bottom >= r.bottom;
} | java | {
"resource": ""
} |
q20051 | Rect.union | train | public void union(Rect r) {
union(r.left, r.top, r.right, r.bottom);
} | java | {
"resource": ""
} |
q20052 | Rect.scale | train | public void scale(float scale) {
if (scale != 1.0f) {
left = (int) (left * scale + 0.5f);
top = (int) (top * scale + 0.5f);
right = (int) (right * scale + 0.5f);
bottom = (int) (bottom * scale + 0.5f);
}
} | java | {
"resource": ""
} |
q20053 | PluginCache.add | train | public void add(Collection<Plugin> plugins)
{
for(Plugin plugin : plugins)
this.plugins.put(plugin.getId(), plugin);
} | java | {
"resource": ""
} |
q20054 | PluginCache.components | train | public PluginComponentCache components(long pluginId)
{
PluginComponentCache cache = components.get(pluginId);
if(cache == null)
components.put(pluginId, cache = new PluginComponentCache(pluginId));
return cache;
} | java | {
"resource": ""
} |
q20055 | Field.getTypeConverter | train | public TypeConverter getTypeConverter() throws RpcException {
if (contract == null) {
throw new IllegalStateException("contract cannot be null");
}
if (type == null) {
throw new IllegalStateException("field type cannot be null");
}
TypeConverter tc = null;
if (type.equals("string"))
tc = new StringTypeConverter(isOptional);
else if (type.equals("int"))
tc = new IntTypeConverter(isOptional);
else if (type.equals("float"))
tc = new FloatTypeConverter(isOptional);
else if (type.equals("bool"))
tc = new BoolTypeConverter(isOptional);
else {
Struct s = contract.getStructs().get(type);
if (s != null) {
tc = new StructTypeConverter(s, isOptional);
}
Enum e = contract.getEnums().get(type);
if (e != null) {
tc = new EnumTypeConverter(e, isOptional);
}
}
if (tc == null) {
throw RpcException.Error.INTERNAL.exc("Unknown type: " + type);
}
else if (isArray) {
return new ArrayTypeConverter(tc, isOptional);
}
else {
return tc;
}
} | java | {
"resource": ""
} |
q20056 | Field.getJavaType | train | public String getJavaType(boolean wrapArray) {
String t = "";
if (type.equals("string")) {
t = "String";
}
else if (type.equals("float")) {
t = "Double";
}
else if (type.equals("int")) {
t = "Long";
}
else if (type.equals("bool")) {
t = "Boolean";
}
else {
t = type;
}
if (wrapArray && isArray) {
return t + "[]";
}
else {
return t;
}
} | java | {
"resource": ""
} |
q20057 | StringUtils.isBlank | train | public static boolean isBlank(final String source) {
if (isEmpty(source)) {
return true;
}
int strLen = source.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(source.charAt(i))) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q20058 | StringUtils.indexOfIgnoreCase | train | public static int indexOfIgnoreCase(final String source, final String target) {
int targetIndex = source.indexOf(target);
if (targetIndex == INDEX_OF_NOT_FOUND) {
String sourceLowerCase = source.toLowerCase();
String targetLowerCase = target.toLowerCase();
targetIndex = sourceLowerCase.indexOf(targetLowerCase);
return targetIndex;
} else {
return targetIndex;
}
} | java | {
"resource": ""
} |
q20059 | StringUtils.containsWord | train | public static boolean containsWord(final String text, final String word) {
if (text == null || word == null) {
return false;
}
if (text.contains(word)) {
Matcher matcher = matchText(text);
for (; matcher.find();) {
String matchedWord = matcher.group(0);
if (matchedWord.equals(word)) {
return true;
}
}
}
return false;
} | java | {
"resource": ""
} |
q20060 | StringUtils.containsWordIgnoreCase | train | public static boolean containsWordIgnoreCase(final String text, final String word) {
if (text == null || word == null) {
return false;
}
return containsWord(text.toLowerCase(), word.toLowerCase());
} | java | {
"resource": ""
} |
q20061 | StringUtils.startsWithIgnoreCase | train | public static boolean startsWithIgnoreCase(final String source, final String target) {
if (source.startsWith(target)) {
return true;
}
if (source.length() < target.length()) {
return false;
}
return source.substring(0, target.length()).equalsIgnoreCase(target);
} | java | {
"resource": ""
} |
q20062 | StringUtils.endsWithIgnoreCase | train | public static boolean endsWithIgnoreCase(final String source, final String target) {
if (source.endsWith(target)) {
return true;
}
if (source.length() < target.length()) {
return false;
}
return source.substring(source.length() - target.length()).equalsIgnoreCase(target);
} | java | {
"resource": ""
} |
q20063 | StringUtils.getRandomString | train | public static String getRandomString(final int stringLength) {
StringBuilder stringBuilder = getStringBuild();
for (int i = 0; i < stringLength; i++) {
stringBuilder.append(getRandomAlphabetic());
}
return stringBuilder.toString();
} | java | {
"resource": ""
} |
q20064 | StringUtils.encoding | train | public static String encoding(final String source, final String sourceCharset,
final String encodingCharset) throws IllegalArgumentException {
byte[] sourceBytes;
String encodeString = null;
try {
sourceBytes = source.getBytes(sourceCharset);
encodeString = new String(sourceBytes, encodingCharset);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(String.format("Unsupported encoding:%s or %s",
sourceCharset, encodingCharset));
}
return encodeString;
} | java | {
"resource": ""
} |
q20065 | NumUtils.getBorders | train | public static double[] getBorders(int numberOfBins, List<Double> counts) {
Collections.sort(counts);
if (!counts.isEmpty()) {
List<Integer> borderInds = findBordersNaive(numberOfBins, counts);
if (borderInds == null) {
borderInds = findBorderIndsByRepeatedDividing(numberOfBins, counts);
}
double[] result = new double[borderInds.size()];
for (int i = 0; i < result.length; i++) {
result[i] = counts.get(borderInds.get(i));
}
return result;
} else
return new double[]{0.0};
} | java | {
"resource": ""
} |
q20066 | Dependencies.getDependencies | train | public Map<String,Set<String>> getDependencies() {
Map<String,Set<String>> new_deps = new HashMap<String,Set<String>>();
if (explicitPackages == null) return new_deps;
for (Name pkg : explicitPackages) {
Set<Name> set = deps.get(pkg);
if (set != null) {
Set<String> new_set = new_deps.get(pkg.toString());
if (new_set == null) {
new_set = new HashSet<String>();
// Modules beware....
new_deps.put(":"+pkg.toString(), new_set);
}
for (Name d : set) {
new_set.add(":"+d.toString());
}
}
}
return new_deps;
} | java | {
"resource": ""
} |
q20067 | Dependencies.visitPubapi | train | public void visitPubapi(Element e) {
Name n = ((ClassSymbol)e).fullname;
Name p = ((ClassSymbol)e).packge().fullname;
StringBuffer sb = publicApiPerClass.get(n);
assert(sb == null);
sb = new StringBuffer();
PubapiVisitor v = new PubapiVisitor(sb);
v.visit(e);
if (sb.length()>0) {
publicApiPerClass.put(n, sb);
}
explicitPackages.add(p);
} | java | {
"resource": ""
} |
q20068 | Dependencies.collect | train | public void collect(Name currPkg, Name depPkg) {
if (!currPkg.equals(depPkg)) {
Set<Name> theset = deps.get(currPkg);
if (theset==null) {
theset = new HashSet<Name>();
deps.put(currPkg, theset);
}
theset.add(depPkg);
}
} | java | {
"resource": ""
} |
q20069 | Pool.preload | train | @SuppressWarnings("unchecked")
public void preload(int quantity) {
Object[] objects = new Object[quantity];
for (int i = 0; i < quantity; i++) {
objects[i] = this.instantiate();
}
for (int i = 0; i < quantity; i++) {
this.release((T)objects[i]);
}
} | java | {
"resource": ""
} |
q20070 | Delayer.blockMe | train | private void blockMe(int cyclesToBlock) {
long unblock = cycles + cyclesToBlock;
BlockedEntry newEntry = new BlockedEntry(unblock);
blockedCollection.add(newEntry);
while (unblock > cycles) {
try {
newEntry.getSync().acquire(); // blocks
} catch (InterruptedException exc) {
log.error("[temporaryBlock] Spurious wakeup", exc);
}
}
} | java | {
"resource": ""
} |
q20071 | Delayer.tick | train | public void tick() {
log.trace("Tick {}", cycles);
cycles++;
// check for robots up for unblocking
for (BlockedEntry entry : blockedCollection) {
if (entry.getTimeout() >= cycles) {
entry.getSync().release();
}
}
} | java | {
"resource": ""
} |
q20072 | Delayer.waitFor | train | public void waitFor(Integer clientId, int turns, String reason) {
// for safety, check if we know the robot, otherwise fail
if (!registered.contains(clientId)) {
throw new IllegalArgumentException("Unknown robot. All robots must first register with clock");
}
synchronized (waitingList) {
if (waitingList.contains(clientId)) {
throw new IllegalArgumentException("Client " + clientId
+ " is already waiting, no multithreading is allowed");
}
waitingList.add(clientId);
}
// we are in the robot's thread
log.trace("[waitFor] Blocking {} for {} turns. Reason: {}", clientId, turns, reason);
blockMe(turns);
log.trace("[waitFor] Unblocked {} - {}", clientId, reason);
synchronized (waitingList) {
waitingList.remove(clientId);
}
} | java | {
"resource": ""
} |
q20073 | NonceShop.produce | train | public String produce(int size) {
byte bytes[] = new byte[size];
_random.nextBytes(bytes);
return Strings.toHexString(bytes);
} | java | {
"resource": ""
} |
q20074 | NonceShop.produce | train | public String produce(String state, long time) {
Nonce nonce = new Nonce(INSTANCE, time > 0 ? time : TTL, SIZE, _random);
_map.put(state + ':' + nonce.value, nonce);
return nonce.value;
} | java | {
"resource": ""
} |
q20075 | NonceShop.renew | train | public boolean renew(String value, String state, long time) {
Nonce nonce = _map.get(state + ':' + value);
if (nonce != null && !nonce.hasExpired()) {
nonce.renew(time > 0 ? time : TTL);
return true;
} else {
return false;
}
} | java | {
"resource": ""
} |
q20076 | NonceShop.prove | train | public boolean prove(String value, String state) {
Nonce nonce = _map.remove(state + ':' + value);
return nonce != null && !nonce.hasExpired();
} | java | {
"resource": ""
} |
q20077 | Enhancements.hasCategory | train | public boolean hasCategory(final String conceptURI) {
return Iterables.any(getCategories(),
new Predicate<TopicAnnotation>() {
@Override
public boolean apply(TopicAnnotation ta) {
return ta.getTopicReference().
equals(conceptURI);
}
}
);
} | java | {
"resource": ""
} |
q20078 | SQLiteDatabase.create | train | public static SQLiteDatabase create(CursorFactory factory) {
// This is a magic string with special meaning for SQLite.
return openDatabase(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration.MEMORY_DB_PATH,
factory, CREATE_IF_NECESSARY);
} | java | {
"resource": ""
} |
q20079 | SQLiteDatabase.replace | train | public long replace(String table, String nullColumnHack, ContentValues initialValues) {
try {
return insertWithOnConflict(table, nullColumnHack, initialValues,
CONFLICT_REPLACE);
} catch (SQLException e) {
DLog.e(TAG, "Error inserting " + initialValues, e);
return -1;
}
} | java | {
"resource": ""
} |
q20080 | BlobKey.decodeBase64Digest | train | private static byte[] decodeBase64Digest(String base64Digest) {
String expectedPrefix = "sha1-";
if (!base64Digest.startsWith(expectedPrefix)) {
throw new IllegalArgumentException(base64Digest + " did not start with " +
expectedPrefix);
}
base64Digest = base64Digest.replaceFirst(expectedPrefix, "");
byte[] bytes = new byte[0];
try {
bytes = Base64.decode(base64Digest);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
return bytes;
} | java | {
"resource": ""
} |
q20081 | ReplicationInternal.fireTrigger | train | protected void fireTrigger(final ReplicationTrigger trigger) {
Log.d(Log.TAG_SYNC, "%s [fireTrigger()] => " + trigger, this);
// All state machine triggers need to happen on the replicator thread
synchronized (executor) {
if (!executor.isShutdown()) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
Log.d(Log.TAG_SYNC, "firing trigger: %s", trigger);
stateMachine.fire(trigger);
} catch (Exception e) {
Log.i(Log.TAG_SYNC, "Error in StateMachine.fire(trigger): %s", e.getMessage());
throw new RuntimeException(e);
}
}
});
}
}
} | java | {
"resource": ""
} |
q20082 | ReplicationInternal.start | train | protected void start() {
try {
if (!db.isOpen()) {
String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db);
parentReplication.setLastError(new Exception(msg));
fireTrigger(ReplicationTrigger.STOP_IMMEDIATE);
return;
}
db.addActiveReplication(parentReplication);
this.authenticating = false;
initSessionId();
// initialize batcher
initBatcher();
// initialize authorizer / authenticator
initAuthorizer();
// initialize request workers
initializeRequestWorkers();
// reset lastSequence
// https://github.com/couchbase/couchbase-lite-java-core/issues/1623
this.lastSequence = null;
// single-shot replication
if (!isContinuous())
goOnline();
// continuous mode
else {
if (isNetworkReachable())
goOnline();
else
triggerGoOffline();
startNetworkReachabilityManager();
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this);
}
} | java | {
"resource": ""
} |
q20083 | ReplicationInternal.close | train | protected void close() {
this.authenticating = false;
// cancel pending futures
for (Future future : pendingFutures) {
future.cancel(false);
CancellableRunnable runnable = cancellables.get(future);
if (runnable != null) {
runnable.cancel();
cancellables.remove(future);
}
}
// shutdown ScheduledExecutorService. Without shutdown, cause thread leak
if (remoteRequestExecutor != null && !remoteRequestExecutor.isShutdown()) {
// Note: Time to wait is set 60 sec because RemoteRequest's socket timeout is set 60 seconds.
Utils.shutdownAndAwaitTermination(remoteRequestExecutor,
Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN,
Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN);
}
// Close and remove all idle connections in the pool,
clientFactory.evictAllConnectionsInPool();
} | java | {
"resource": ""
} |
q20084 | ReplicationInternal.checkSession | train | @InterfaceAudience.Private
protected void checkSession() {
if (getAuthenticator() != null) {
Authorizer auth = (Authorizer) getAuthenticator();
auth.setRemoteURL(remote);
auth.setLocalUUID(db.publicUUID());
}
if (getAuthenticator() != null && getAuthenticator() instanceof SessionCookieAuthorizer) {
// Sync Gateway session API is at /db/_session; try that first
checkSessionAtPath("_session");
} else {
login();
}
} | java | {
"resource": ""
} |
q20085 | ReplicationInternal.refreshRemoteCheckpointDoc | train | @InterfaceAudience.Private
private void refreshRemoteCheckpointDoc() {
Log.i(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this);
Future future = sendAsyncRequest("GET", "_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletion() {
@Override
public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {
if (db == null) {
Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint. aborting", this);
return;
}
if (e != null && Utils.getStatusFromError(e) != Status.NOT_FOUND) {
Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this);
} else {
Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result);
remoteCheckpoint = (Map<String, Object>) result;
lastSequenceChanged = true;
saveLastSequence(); // try saving again
}
}
});
pendingFutures.add(future);
} | java | {
"resource": ""
} |
q20086 | ReplicationInternal.stop | train | protected void stop() {
this.authenticating = false;
// clear batcher
batcher.clear();
// set non-continuous
setLifecycle(Replication.Lifecycle.ONESHOT);
// cancel if middle of retry
cancelRetryFuture();
// cancel all pending future tasks.
while (!pendingFutures.isEmpty()) {
Future future = pendingFutures.poll();
if (future != null && !future.isCancelled() && !future.isDone()) {
future.cancel(true);
CancellableRunnable runnable = cancellables.get(future);
if (runnable != null) {
runnable.cancel();
cancellables.remove(future);
}
}
}
} | java | {
"resource": ""
} |
q20087 | ReplicationInternal.notifyChangeListeners | train | private void notifyChangeListeners(final Replication.ChangeEvent changeEvent) {
if (changeListenerNotifyStyle == ChangeListenerNotifyStyle.SYNC) {
for (ChangeListener changeListener : changeListeners) {
try {
changeListener.changed(changeEvent);
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Unknown Error in changeListener.changed(changeEvent)", e);
}
}
} else {
// ASYNC
synchronized (executor) {
if (!executor.isShutdown()) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
for (ChangeListener changeListener : changeListeners)
changeListener.changed(changeEvent);
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Exception notifying replication listener: %s", e, this);
throw new RuntimeException(e);
}
}
});
}
}
}
} | java | {
"resource": ""
} |
q20088 | ReplicationInternal.scheduleRetryFuture | train | private void scheduleRetryFuture() {
Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec", this, RETRY_DELAY_SECONDS);
synchronized (executor) {
if (!executor.isShutdown()) {
this.retryFuture = executor.schedule(new Runnable() {
public void run() {
retryIfReady();
}
}, RETRY_DELAY_SECONDS, TimeUnit.SECONDS);
}
}
} | java | {
"resource": ""
} |
q20089 | ReplicationInternal.cancelRetryFuture | train | private void cancelRetryFuture() {
if (retryFuture != null && !retryFuture.isDone()) {
retryFuture.cancel(true);
}
retryFuture = null;
} | java | {
"resource": ""
} |
q20090 | ReplicationInternal.retryReplicationIfError | train | protected void retryReplicationIfError() {
Log.d(TAG, "retryReplicationIfError() state=" + stateMachine.getState() +
", error=" + this.error +
", isContinuous()=" + isContinuous() +
", isTransientError()=" + Utils.isTransientError(this.error));
// Make sure if state is IDLE, this method should be called when state becomes IDLE
if (!stateMachine.getState().equals(ReplicationState.IDLE))
return;
if (this.error != null) {
// IDLE_ERROR
if (isContinuous()) {
// 12/16/2014 - only retry if error is transient error 50x http error
// It may need to retry for any kind of errors
if (Utils.isTransientError(this.error)) {
onBeforeScheduleRetry();
cancelRetryFuture();
scheduleRetryFuture();
}
}
}
} | java | {
"resource": ""
} |
q20091 | SQLiteConnection.dumpUnsafe | train | void dumpUnsafe(Printer printer, boolean verbose) {
printer.println("Connection #" + mConnectionId + ":");
if (verbose) {
printer.println(" connectionPtr: 0x" + Long.toHexString(mConnectionPtr));
}
printer.println(" isPrimaryConnection: " + mIsPrimaryConnection);
printer.println(" onlyAllowReadOnlyOperations: " + mOnlyAllowReadOnlyOperations);
mRecentOperations.dump(printer, verbose);
} | java | {
"resource": ""
} |
q20092 | SQLiteConnection.collectDbStatsUnsafe | train | void collectDbStatsUnsafe(ArrayList<com.couchbase.lite.internal.database.sqlite.SQLiteDebug.DbStats> dbStatsList) {
dbStatsList.add(getMainDbStatsUnsafe(0, 0, 0));
} | java | {
"resource": ""
} |
q20093 | RemoteRequest.execute | train | protected void execute() {
Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() called, url: %s", this, url);
executeRequest(factory.getOkHttpClient(), request());
Log.v(Log.TAG_SYNC, "%s: RemoteRequest execute() finished, url: %s", this, url);
} | java | {
"resource": ""
} |
q20094 | RemoteRequest.setCompressedBody | train | protected RequestBody setCompressedBody(byte[] bodyBytes) {
if (bodyBytes.length < MIN_JSON_LENGTH_TO_COMPRESS)
return null;
byte[] encodedBytes = Utils.compressByGzip(bodyBytes);
if (encodedBytes == null || encodedBytes.length >= bodyBytes.length)
return null;
return RequestBody.create(JSON, encodedBytes);
} | java | {
"resource": ""
} |
q20095 | KMPMatch.indexOf | train | int indexOf(byte[] data, int dataLength, byte[] pattern, int dataOffset) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0)
return -1;
//final int dataLength = data.length;
final int patternLength = pattern.length;
for (int i = dataOffset; i < dataLength; i++) {
while (j > 0 && pattern[j] != data[i])
j = failure[j - 1];
if (pattern[j] == data[i])
j++;
if (j == patternLength)
return i - patternLength + 1;
}
return -1;
} | java | {
"resource": ""
} |
q20096 | KMPMatch.computeFailure | train | private static int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i])
j = failure[j - 1];
if (pattern[j] == pattern[i])
j++;
failure[i] = j;
}
return failure;
} | java | {
"resource": ""
} |
q20097 | Manager.getAllDatabaseNames | train | @InterfaceAudience.Public
public List<String> getAllDatabaseNames() {
String[] databaseFiles = directoryFile.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(Manager.kDBExtension)) {
return true;
}
return false;
}
});
List<String> result = new ArrayList<String>();
for (String databaseFile : databaseFiles) {
String trimmed = databaseFile.substring(0, databaseFile.length() - Manager.kDBExtension.length());
String replaced = trimmed.replace(':', '/');
result.add(replaced);
}
Collections.sort(result);
return Collections.unmodifiableList(result);
} | java | {
"resource": ""
} |
q20098 | Manager.close | train | @InterfaceAudience.Public
public void close() {
synchronized (lockDatabases) {
Log.d(Database.TAG, "Closing " + this);
// Close all database:
// Snapshot of the current open database to avoid concurrent modification as
// the database will be forgotten (removed from the databases map) when it is closed:
Database[] openDbs = databases.values().toArray(new Database[databases.size()]);
for (Database database : openDbs)
database.close();
databases.clear();
// Stop reachability:
context.getNetworkReachabilityManager().stopListening();
// Shutdown ScheduledExecutorService:
if (workExecutor != null && !workExecutor.isShutdown())
Utils.shutdownAndAwaitTermination(workExecutor);
Log.d(Database.TAG, "Closed " + this);
}
} | java | {
"resource": ""
} |
q20099 | Manager.replaceDatabase | train | @InterfaceAudience.Public
public boolean replaceDatabase(String databaseName, String databaseDir) {
Database db = getDatabase(databaseName, false);
if(db == null)
return false;
File dir = new File(databaseDir);
if(!dir.exists()){
Log.w(Database.TAG, "Database file doesn't exist at path : %s", databaseDir);
return false;
}
if (!dir.isDirectory()) {
Log.w(Database.TAG, "Database file is not a directory. " +
"Use -replaceDatabaseNamed:withDatabaseFilewithAttachments:error: instead.");
return false;
}
File destDir = new File(db.getPath());
File srcDir = new File(databaseDir);
if(destDir.exists()) {
if (!FileDirUtils.deleteRecursive(destDir)) {
Log.w(Database.TAG, "Failed to delete file/directly: " + destDir);
return false;
}
}
try {
FileDirUtils.copyFolder(srcDir, destDir);
} catch (IOException e) {
Log.w(Database.TAG, "Failed to copy directly from " + srcDir + " to " + destDir, e);
return false;
}
try {
db.open();
} catch (CouchbaseLiteException e) {
Log.w(Database.TAG, "Failed to open database", e);
return false;
}
/* TODO: Currently Java implementation is different from iOS, needs to catch up.
if(!db.saveLocalUUIDInLocalCheckpointDocument()){
Log.w(Database.TAG, "Failed to replace UUIDs");
return false;
}
*/
if(!db.replaceUUIDs()){
Log.w(Database.TAG, "Failed to replace UUIDs");
db.close();
return false;
}
// close so app can (re)open db with its preferred options:
db.close();
return true;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.