_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14200 | SSLTools.validCertificateString | train | public static boolean validCertificateString(String certificateString) {
try {
byte[] certBytes = parseDERFromPEM(certificateString, CERT_START, CERT_END);
generateCertificateFromDER(certBytes);
} catch (Exception e) {
return false;
}
return true;
} | java | {
"resource": ""
} |
q14201 | RESTClient.urlParameter | train | public RESTClient<RS, ERS> urlParameter(String name, Object value) {
if (value == null) {
return this;
}
List<Object> values = this.parameters.get(name);
if (values == null) {
values = new ArrayList<>();
this.parameters.put(name, values);
}
if (value instanceof ZonedDateTime) {
values.add(((ZonedDateTime) value).toInstant().toEpochMilli());
} else if (value instanceof Collection) {
values.addAll((Collection) value);
} else {
values.add(value);
}
return this;
} | java | {
"resource": ""
} |
q14202 | WebSocketClassLoader.findResources | train | @Override
protected Enumeration<URL> findResources(String name) {
URL url = findResource(name);
Vector<URL> urls = new Vector<>();
if (url != null) {
urls.add(url);
}
return urls.elements();
} | java | {
"resource": ""
} |
q14203 | ConfigurationsCatalog.unsetUserConfigurations | train | public void unsetUserConfigurations(UserConfigurationsProvider provider) {
if (userConfigurations.isPresent() && userConfigurations.get().equals(provider)) {
this.userConfigurations = Optional.empty();
}
} | java | {
"resource": ""
} |
q14204 | Artefact.getAttribute | train | public Attribute getAttribute(final String attributeName) {
final Attribute a = attributes.get(attributeName);
if (a == null)
throw new IllegalArgumentException("Attribute " + attributeName + " doesn't exists");
return a;
} | java | {
"resource": ""
} |
q14205 | Artefact.addAttributeValue | train | public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) {
if (in == null)
in = GlobalEnvironment.INSTANCE;
Attribute attr = attributes.get(attributeName);
if (attr == null) {
attr = new Attribute(attributeName);
attributes.put(attr.getName(), attr);
}
attr.addValue(attributeValue, in);
Map<String, Object> valueMap = contentMap.get(in);
if(valueMap == null)
valueMap = new HashMap<>();
valueMap.put(attributeName, attributeValue.getRaw());
contentMap.put(in, valueMap);
//TODO check for loops and process such situation
if (attributeValue instanceof IncludeValue)
externalConfigurations.add(((IncludeValue) attributeValue).getConfigName());
} | java | {
"resource": ""
} |
q14206 | HttpServer.onClose | train | @Handler
public void onClose(Close event, WebAppMsgChannel appChannel)
throws InterruptedException {
appChannel.handleClose(event);
} | java | {
"resource": ""
} |
q14207 | HttpServer.onOptions | train | @Handler(priority = Integer.MIN_VALUE)
public void onOptions(Request.In.Options event, IOSubchannel appChannel) {
if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) {
HttpResponse response = event.httpRequest().response().get();
response.setStatus(HttpStatus.OK);
appChannel.respond(new Response(response));
event.setResult(true);
event.stop();
}
} | java | {
"resource": ""
} |
q14208 | Pattern.matcher | train | public Matcher matcher(CharSequence s) {
Matcher m = new Matcher(this);
m.setTarget(s);
return m;
} | java | {
"resource": ""
} |
q14209 | Pattern.matcher | train | public Matcher matcher(char[] data, int start, int end) {
Matcher m = new Matcher(this);
m.setTarget(data, start, end);
return m;
} | java | {
"resource": ""
} |
q14210 | Pattern.matcher | train | public Matcher matcher(MatchResult res, String groupName) {
Integer id = res.pattern().groupId(groupName);
if (id == null) throw new IllegalArgumentException("group not found:" + groupName);
int group = id;
return matcher(res, group);
} | java | {
"resource": ""
} |
q14211 | ColumnRelation.toList | train | public List<ColumnRelation> toList() {
List<ColumnRelation> ret = new ArrayList<>();
ret.add(this);
if (getNextRelation().isPresent()) {
ret.addAll(getNextRelation().get().toList());
}
return ret;
} | java | {
"resource": ""
} |
q14212 | DataSourceUtils.addToDataSource | train | public static void addToDataSource(DataSource parent, DataSource child) {
if (!parent.getLeftDataSource().isPresent()) {
parent.setLeftDataSource(child);
} else if (!parent.getRightDataSource().isPresent()) {
parent.setRightDataSource(child);
} else {
DataSource newLeftDataSource = new DataSource(parent.getLeftDataSource().get());
newLeftDataSource.setRightDataSource(parent.getRightDataSource().get());
parent.setLeftDataSource(newLeftDataSource);
parent.setRightDataSource(child);
}
} | java | {
"resource": ""
} |
q14213 | DefaultFormatter.format | train | @Override
public String format (LogRecord logRecord) {
StringBuilder resultBuilder = new StringBuilder ();
String prefix = logRecord.getLevel ().getName () + "\t";
resultBuilder.append (prefix);
resultBuilder.append (Thread.currentThread ().getName ())
.append (" ")
.append (sdf.format (new java.util.Date (logRecord.getMillis ())))
.append (": ")
.append (logRecord.getSourceClassName ())
.append (":")
.append (logRecord.getSourceMethodName ())
.append (": ")
.append (logRecord.getMessage ());
Object[] params = logRecord.getParameters ();
if (params != null) {
resultBuilder.append ("\nParameters:");
if (params.length < 1) {
resultBuilder.append (" (none)");
} else {
for (int paramIndex = 0; paramIndex < params.length; paramIndex++) {
Object param = params[paramIndex];
if (param != null) {
String paramString = param.toString ();
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is a ")
.append (param.getClass ().getName ())
.append (": >")
.append (paramString)
.append ("<");
} else {
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is null.");
}
}
}
}
Throwable t = logRecord.getThrown ();
if (t != null) {
resultBuilder.append ("\nThrowing:\n")
.append (getFullThrowableMsg (t));
}
String result = resultBuilder.toString ().replaceAll ("\n", "\n" + prefix) + "\n";
return result;
} | java | {
"resource": ""
} |
q14214 | UserOption.acceptsValue | train | public boolean acceptsValue(String value) {
if (value==null) {
return false;
} else if (hasValues()) {
return getValuesList().contains(value);
} else {
return true;
}
} | java | {
"resource": ""
} |
q14215 | JacksonRequest.getUrl | train | private static String getUrl(int method, String baseUrl, String endpoint, Map<String, String> params) {
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() == null || entry.getValue().equals("null")) {
entry.setValue("");
}
}
}
if (method == Method.GET && params != null && !params.isEmpty()) {
final StringBuilder result = new StringBuilder(baseUrl + endpoint);
final int startLength = result.length();
for (String key : params.keySet()) {
try {
final String encodedKey = URLEncoder.encode(key, "UTF-8");
final String encodedValue = URLEncoder.encode(params.get(key), "UTF-8");
if (result.length() > startLength) {
result.append("&");
} else {
result.append("?");
}
result.append(encodedKey);
result.append("=");
result.append(encodedValue);
} catch (Exception e) { }
}
return result.toString();
} else {
return baseUrl + endpoint;
}
} | java | {
"resource": ""
} |
q14216 | LogHelperConfigurator.configure | train | public static boolean configure (File configFile) {
boolean goOn = true;
if (!configFile.exists ()) {
LogHelperDebug.printError ("File " + configFile.getAbsolutePath () + " does not exist", false);
goOn = false;
}
DocumentBuilderFactory documentBuilderFactory = null;
DocumentBuilder documentBuilder = null;
if (goOn) {
documentBuilderFactory = DocumentBuilderFactory.newInstance ();
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder ();
} catch (ParserConfigurationException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
Document configDocument = null;
if (goOn) {
try {
configDocument = documentBuilder.parse (configFile);
} catch (SAXException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
} catch (IOException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
NodeList configNodeList = null;
if (goOn) {
configNodeList = configDocument.getElementsByTagName ("log-helper");
if (configNodeList == null) {
LogHelperDebug.printError ("configNodeList is null", false);
goOn = false;
} else if (configNodeList.getLength () < 1) {
LogHelperDebug.printError ("configNodeList is empty", false);
goOn = false;
}
}
Node configNode = null;
if (goOn) {
configNode = configNodeList.item (0);
if (configNode == null) {
LogHelperDebug.printError ("configNode is null", false);
goOn = false;
}
}
boolean success = false;
if (goOn) {
success = configure (configNode);
}
return success;
} | java | {
"resource": ""
} |
q14217 | LogHelperConfigurator.configureLoggerWrapper | train | private static void configureLoggerWrapper (Node configNode) {
Node lwNameNode = configNode.getAttributes ().getNamedItem ("name");
String lwName;
if (lwNameNode != null) {
lwName = lwNameNode.getTextContent ();
} else {
lwName = "LoggerWrapper_" + String.valueOf ((new Date ()).getTime ());
}
LoggerWrapper loggerWrapper = LogHelper.getLoggerWrapper (lwName);
NodeList lwSubnodes = configNode.getChildNodes ();
for (int subnodeIndex = 0; subnodeIndex < lwSubnodes.getLength (); subnodeIndex++) {
Node subnode = lwSubnodes.item (subnodeIndex);
String subnodeName = subnode.getNodeName ().trim ().toLowerCase ();
if (subnodeName.equals ("configurator")) {
configureLoggerWrapperByConfigurator (loggerWrapper, subnode);
}
}
} | java | {
"resource": ""
} |
q14218 | PermitsPool.removeListener | train | public PermitsPool removeListener(AvailabilityListener listener) {
synchronized (listeners) {
for (Iterator<WeakReference<AvailabilityListener>> iter
= listeners.iterator(); iter.hasNext();) {
WeakReference<AvailabilityListener> item = iter.next();
if (item.get() == null || item.get() == listener) {
iter.remove();
}
}
}
return this;
} | java | {
"resource": ""
} |
q14219 | Components.className | train | public static String className(Class<?> clazz) {
if (CoreUtils.classNames.isLoggable(Level.FINER)) {
return clazz.getName();
} else {
return simpleClassName(clazz);
}
} | java | {
"resource": ""
} |
q14220 | Components.schedule | train | public static Timer schedule(
TimeoutHandler timeoutHandler, Instant scheduledFor) {
return scheduler.schedule(timeoutHandler, scheduledFor);
} | java | {
"resource": ""
} |
q14221 | Components.schedule | train | public static Timer schedule(
TimeoutHandler timeoutHandler, Duration scheduledFor) {
return scheduler.schedule(
timeoutHandler, Instant.now().plus(scheduledFor));
} | java | {
"resource": ""
} |
q14222 | Util.encodePostBody | train | @Deprecated
public static String encodePostBody(Bundle parameters, String boundary) {
if (parameters == null) return "";
StringBuilder sb = new StringBuilder();
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
sb.append("Content-Disposition: form-data; name=\"" + key +
"\"\r\n\r\n" + (String)parameter);
sb.append("\r\n" + "--" + boundary + "\r\n");
}
return sb.toString();
} | java | {
"resource": ""
} |
q14223 | Util.parseUrl | train | @Deprecated
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
} | java | {
"resource": ""
} |
q14224 | Util.openUrl | train | @Deprecated
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);
}
Utility.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());
try {
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();
} finally {
os.close();
}
}
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;
}
@Deprecated
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();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
@Deprecated
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": ""
} |
q14225 | NativeAppCallContentProvider.getAttachmentUrl | train | public static String getAttachmentUrl(String applicationId, UUID callId, String attachmentName) {
return String.format("%s%s/%s/%s", ATTACHMENT_URL_BASE, applicationId, callId.toString(), attachmentName);
} | java | {
"resource": ""
} |
q14226 | CharArrayList.set | train | @Deprecated
public Character set(final int index, final Character ok) {
return set(index, ok.charValue());
} | java | {
"resource": ""
} |
q14227 | CharArrayList.getElements | train | private void getElements(final int from, final char[] a, final int offset, final int length) {
CharArrays.ensureOffsetLength(a, offset, length);
System.arraycopy(this.a, from, a, offset, length);
} | java | {
"resource": ""
} |
q14228 | CharArrayList.removeElements | train | public void removeElements(final int from, final int to) {
CharArrays.ensureFromTo(size, from, to);
System.arraycopy(a, to, a, from, size - to);
size -= (to - from);
} | java | {
"resource": ""
} |
q14229 | CharArrayList.addElements | train | public void addElements(final int index, final char a[], final int offset, final int length) {
ensureIndex(index);
CharArrays.ensureOffsetLength(a, offset, length);
grow(size + length);
System.arraycopy(this.a, index, this.a, index + length, size - index);
System.arraycopy(a, offset, this.a, index, length);
size += length;
} | java | {
"resource": ""
} |
q14230 | CharArrayList.ensureIndex | train | private void ensureIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index > size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")");
} | java | {
"resource": ""
} |
q14231 | CharArrayList.ensureRestrictedIndex | train | protected void ensureRestrictedIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index >= size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")");
} | java | {
"resource": ""
} |
q14232 | CharArrayList.containsAll | train | public boolean containsAll(Collection<?> c) {
int n = c.size();
final Iterator<?> i = c.iterator();
while (n-- != 0)
if (!contains(i.next())) return false;
return true;
} | java | {
"resource": ""
} |
q14233 | CharArrayList.addAll | train | public boolean addAll(Collection<? extends Character> c) {
boolean retVal = false;
final Iterator<? extends Character> i = c.iterator();
int n = c.size();
while (n-- != 0)
if (add(i.next())) retVal = true;
return retVal;
} | java | {
"resource": ""
} |
q14234 | UserConfigurationsCollection.getConfigurationDetails | train | public synchronized Set<ConfigurationDetails> getConfigurationDetails() {
return inventory.entries().stream()
.map(c->c.getConfiguration().orElse(null))
.filter(v->v!=null)
.map(v->v.getDetails())
.collect(Collectors.toSet());
} | java | {
"resource": ""
} |
q14235 | UserConfigurationsCollection.getConfiguration | train | public synchronized Map<String, Object> getConfiguration(String key) {
return Optional.ofNullable(inventory.get(key))
.flatMap(v->v.getConfiguration())
.map(v->v.getMap())
.orElse(null);
} | java | {
"resource": ""
} |
q14236 | UserConfigurationsCollection.addConfiguration | train | public synchronized Optional<String> addConfiguration(String niceName, String description, Map<String, Object> config) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()-> {
ConfigurationDetails p = new ConfigurationDetails.Builder(inventory.nextIdentifier())
.niceName(niceName)
.description(description).build();
try {
InventoryEntry ret = InventoryEntry.create(new Configuration(p, new HashMap<>(config)), newConfigurationFile());
inventory.add(ret);
return Optional.of(ret.getIdentifier());
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to add configuration.", e);
return Optional.empty();
}
});
} catch (IOException e) {
logger.log(Level.WARNING, "Could not add configuration", e);
return Optional.empty();
}
} | java | {
"resource": ""
} |
q14237 | UserConfigurationsCollection.removeConfiguration | train | public synchronized boolean removeConfiguration(String key) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()->inventory.remove(key)!=null);
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to remove configuration.", e);
return false;
}
} | java | {
"resource": ""
} |
q14238 | UserConfigurationsCollection.cleanupInventory | train | private boolean cleanupInventory() {
boolean modified = false;
modified |= removeUnreadable();
modified |= recreateMismatching();
modified |= importConfigurations();
return modified;
} | java | {
"resource": ""
} |
q14239 | UserConfigurationsCollection.removeUnreadable | train | private boolean removeUnreadable() {
List<File> unreadable = inventory.removeUnreadable();
unreadable.forEach(v->v.delete());
return !unreadable.isEmpty();
} | java | {
"resource": ""
} |
q14240 | UserConfigurationsCollection.recreateMismatching | train | private boolean recreateMismatching() {
List<Configuration> mismatching = inventory.removeMismatching();
mismatching.forEach(entry->{
try {
inventory.add(InventoryEntry.create(entry.copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
} catch (IOException e1) {
logger.log(Level.WARNING, "Failed to write a configuration.", e1);
}
});
return !mismatching.isEmpty();
} | java | {
"resource": ""
} |
q14241 | UserConfigurationsCollection.importConfigurations | train | private boolean importConfigurations() {
// Create a set of files in the inventory
Set<File> files = inventory.entries().stream().map(v->v.getPath()).collect(Collectors.toSet());
List<File> entriesToImport = Arrays.asList(baseDir.listFiles(f->
f.isFile()
&& !f.equals(catalog) // Exclude the master catalog (should it have the same extension as entries)
&& f.getName().endsWith(CONFIG_EXT)
&& !files.contains(f)) // Exclude files already in the inventory
);
entriesToImport.forEach(f->{
try {
inventory.add(InventoryEntry.create(Configuration.read(f).copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
f.delete();
} catch (IOException e) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Failed to read: " + f, e);
}
}
});
return !entriesToImport.isEmpty();
} | java | {
"resource": ""
} |
q14242 | Event.channels | train | @SuppressWarnings({ "unchecked", "PMD.ShortVariable",
"PMD.AvoidDuplicateLiterals" })
public <C> C[] channels(Class<C> type) {
return Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass())).toArray(
size -> (C[]) Array.newInstance(type, size));
} | java | {
"resource": ""
} |
q14243 | Event.forChannels | train | @SuppressWarnings({ "unchecked", "PMD.ShortVariable" })
public <E extends EventBase<?>, C extends Channel> void forChannels(
Class<C> type, BiConsumer<E, C> handler) {
Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass()))
.forEach(c -> handler.accept((E) this, (C) c));
} | java | {
"resource": ""
} |
q14244 | Event.setResult | train | public Event<T> setResult(T result) {
synchronized (this) {
if (results == null) {
// Make sure that we have a valid result before
// calling decrementOpen
results = new ArrayList<T>();
results.add(result);
firstResultAssigned();
return this;
}
results.add(result);
return this;
}
} | java | {
"resource": ""
} |
q14245 | Event.currentResults | train | protected List<T> currentResults() {
return results == null ? Collections.emptyList()
: Collections.unmodifiableList(results);
} | java | {
"resource": ""
} |
q14246 | PeasyViewHolder.inflateView | train | public static View inflateView(LayoutInflater inflater, ViewGroup parent, int layoutId) {
return inflater.inflate(layoutId, parent, false);
} | java | {
"resource": ""
} |
q14247 | PeasyViewHolder.GetViewHolder | train | public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) {
return cls.cast(vh);
} | java | {
"resource": ""
} |
q14248 | PeasyViewHolder.bindWith | train | <T> void bindWith(final PeasyRecyclerView<T> binder, final int viewType) {
this.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (position != RecyclerView.NO_POSITION) {
binder.onItemClick(v, viewType, position, binder.getItem(position), getInstance());
}
}
});
this.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (getLayoutPosition() != RecyclerView.NO_POSITION) {
return binder.onItemLongClick(v, viewType, position, binder.getItem(position), getInstance());
}
return false;
}
});
} | java | {
"resource": ""
} |
q14249 | ComponentTree.fire | train | @SuppressWarnings("PMD.UseVarargs")
public void fire(Event<?> event, Channel[] channels) {
eventPipeline.add(event, channels);
} | java | {
"resource": ""
} |
q14250 | ComponentTree.dispatch | train | @SuppressWarnings("PMD.UseVarargs")
/* default */ void dispatch(EventPipeline pipeline,
EventBase<?> event, Channel[] channels) {
HandlerList handlers = getEventHandlers(event, channels);
handlers.process(pipeline, event);
} | java | {
"resource": ""
} |
q14251 | IOUtils.readlineFromStdIn | train | public static String readlineFromStdIn() throws IOException {
StringBuilder ret = new StringBuilder();
int c;
while ((c = System.in.read()) != '\n' && c != -1) {
if (c != '\r')
ret.append((char) c);
}
return ret.toString();
} | java | {
"resource": ""
} |
q14252 | FacebookFragment.getSessionState | train | protected final SessionState getSessionState() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getState() : null;
}
return null;
} | java | {
"resource": ""
} |
q14253 | FacebookFragment.getAccessToken | train | protected final String getAccessToken() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getAccessToken() : null;
}
return null;
} | java | {
"resource": ""
} |
q14254 | FacebookFragment.getExpirationDate | train | protected final Date getExpirationDate() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getExpirationDate() : null;
}
return null;
} | java | {
"resource": ""
} |
q14255 | FacebookFragment.closeSessionAndClearTokenInformation | train | protected final void closeSessionAndClearTokenInformation() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
}
}
} | java | {
"resource": ""
} |
q14256 | FacebookFragment.getSessionPermissions | train | protected final List<String> getSessionPermissions() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getPermissions() : null;
}
return null;
} | java | {
"resource": ""
} |
q14257 | FacebookFragment.openSessionForRead | train | protected final void openSessionForRead(String applicationId, List<String> permissions,
SessionLoginBehavior behavior, int activityCode) {
openSession(applicationId, permissions, behavior, activityCode, SessionAuthorizationType.READ);
} | java | {
"resource": ""
} |
q14258 | AppLinkData.fetchDeferredAppLinkData | train | public static void fetchDeferredAppLinkData(
Context context,
String applicationId,
final CompletionHandler completionHandler) {
Validate.notNull(context, "context");
Validate.notNull(completionHandler, "completionHandler");
if (applicationId == null) {
applicationId = Utility.getMetadataApplicationId(context);
}
Validate.notNull(applicationId, "applicationId");
final Context applicationContext = context.getApplicationContext();
final String applicationIdCopy = applicationId;
Settings.getExecutor().execute(new Runnable() {
@Override
public void run() {
fetchDeferredAppLinkFromServer(applicationContext, applicationIdCopy, completionHandler);
}
});
} | java | {
"resource": ""
} |
q14259 | AppLinkData.createFromActivity | train | public static AppLinkData createFromActivity(Activity activity) {
Validate.notNull(activity, "activity");
Intent intent = activity.getIntent();
if (intent == null) {
return null;
}
AppLinkData appLinkData = createFromAlApplinkData(intent);
if (appLinkData == null) {
String appLinkArgsJsonString = intent.getStringExtra(BUNDLE_APPLINK_ARGS_KEY);
appLinkData = createFromJson(appLinkArgsJsonString);
}
if (appLinkData == null) {
// Try regular app linking
appLinkData = createFromUri(intent.getData());
}
return appLinkData;
} | java | {
"resource": ""
} |
q14260 | Matcher.setPattern | train | public void setPattern(Pattern regex)
{
this.re = regex;
int memregCount, counterCount, lookaheadCount;
if ((memregCount = regex.memregs) > 0) {
MemReg[] memregs = new MemReg[memregCount];
for (int i = 0; i < memregCount; i++) {
memregs[i] = new MemReg(-1); //unlikely to SearchEntry, in this case we know memreg indices by definition
}
this.memregs = memregs;
}
if ((counterCount = regex.counters) > 0) counters = new int[counterCount];
if ((lookaheadCount = regex.lookaheads) > 0) {
LAEntry[] lookaheads = new LAEntry[lookaheadCount];
for (int i = 0; i < lookaheadCount; i++) {
lookaheads[i] = new LAEntry();
}
this.lookaheads = lookaheads;
}
this.memregCount = memregCount;
this.counterCount = counterCount;
this.lookaheadCount = lookaheadCount;
first = new SearchEntry();
defaultEntry = new SearchEntry();
minQueueLength = regex.stringRepr.length() / 2; // just evaluation!!!
} | java | {
"resource": ""
} |
q14261 | Matcher.skip | train | public void skip() {
int we = wEnd;
if (wOffset == we) { //requires special handling
//if no variants at 'wOutside',advance pointer and clear
if (top == null) {
wOffset++;
flush();
}
//otherwise, if there exist a variant,
//don't clear(), i.e. allow it to match
return;
} else {
if (we < 0) wOffset = 0;
else wOffset = we;
}
//rflush(); //rflush() works faster on simple regexes (with a small group/branch number)
flush();
} | java | {
"resource": ""
} |
q14262 | Matcher.flush | train | public void flush() {
top = null;
defaultEntry.reset(0);
first.reset(minQueueLength);
for (int i = memregs.length - 1; i > 0; i--) {
MemReg mr = memregs[i];
mr.in = mr.out = -1;
}
/*
for (int i = memregs.length - 1; i > 0; i--) {
MemReg mr = memregs[i];
mr.in = mr.out = -1;
}*/
called = false;
} | java | {
"resource": ""
} |
q14263 | Matcher.start | train | @Override
public int start(String name) {
Integer id = re.groupId(name);
if (id == null) throw new IllegalArgumentException("<" + name + "> isn't defined");
return start(id);
} | java | {
"resource": ""
} |
q14264 | Matcher.repeat | train | private static int repeat(char[] data, int off, int out, Term term) {
switch (term.type) {
case Term.CHAR: {
char c = term.c;
int i = off;
while (i < out) {
if (data[i] != c) break;
i++;
}
return i - off;
}
case Term.ANY_CHAR: {
return out - off;
}
case Term.ANY_CHAR_NE: {
int i = off;
char c;
while (i < out) {
if ((c = data[i]) == '\r' || c == '\n') break;
i++;
}
return i - off;
}
case Term.BITSET: {
IntBitSet arr = term.bitset;
int i = off;
char c;
if (term.inverse) while (i < out) {
if ((c = data[i]) <= 255 && arr.get(c)) break;
else i++;
}
else while (i < out) {
if ((c = data[i]) <= 255 && arr.get(c)) i++;
else break;
}
return i - off;
}
case Term.BITSET2: {
int i = off;
IntBitSet[] bitset2 = term.bitset2;
char c;
if (term.inverse) while (i < out) {
IntBitSet arr = bitset2[(c = data[i]) >> 8];
if (arr != null && arr.get(c & 0xff)) break;
else i++;
}
else while (i < out) {
IntBitSet arr = bitset2[(c = data[i]) >> 8];
if (arr != null && arr.get(c & 0xff)) i++;
else break;
}
return i - off;
}
}
throw new Error("this kind of term can't be quantified:" + term.type);
} | java | {
"resource": ""
} |
q14265 | Matcher.find | train | private static int find(char[] data, int off, int out, Term term) {
if (off >= out) return -1;
switch (term.type) {
case Term.CHAR: {
char c = term.c;
int i = off;
while (i < out) {
if (data[i] == c) break;
i++;
}
return i - off;
}
case Term.BITSET: {
IntBitSet arr = term.bitset;
int i = off;
char c;
if (!term.inverse) while (i < out) {
if ((c = data[i]) <= 255 && arr.get(c)) break;
else i++;
}
else while (i < out) {
if ((c = data[i]) <= 255 && arr.get(c)) i++;
else break;
}
return i - off;
}
case Term.BITSET2: {
int i = off;
IntBitSet[] bitset2 = term.bitset2;
char c;
if (!term.inverse) while (i < out) {
IntBitSet arr = bitset2[(c = data[i]) >> 8];
if (arr != null && arr.get(c & 0xff)) break;
else i++;
}
else while (i < out) {
IntBitSet arr = bitset2[(c = data[i]) >> 8];
if (arr != null && arr.get(c & 0xff)) i++;
else break;
}
return i - off;
}
}
throw new IllegalArgumentException("can't seek this kind of term:" + term.type);
} | java | {
"resource": ""
} |
q14266 | FacebookDialog.present | train | public PendingCall present() {
logDialogActivity(activity, fragment, getEventName(appCall.getRequestIntent()),
AnalyticsEvents.PARAMETER_DIALOG_OUTCOME_VALUE_COMPLETED);
if (onPresentCallback != null) {
try {
onPresentCallback.onPresent(activity);
} catch (Exception e) {
throw new FacebookException(e);
}
}
if (fragment != null) {
fragment.startActivityForResult(appCall.getRequestIntent(), appCall.getRequestCode());
} else {
activity.startActivityForResult(appCall.getRequestIntent(), appCall.getRequestCode());
}
return appCall;
} | java | {
"resource": ""
} |
q14267 | FacebookDialog.handleActivityResult | train | public static boolean handleActivityResult(Context context, PendingCall appCall, int requestCode, Intent data,
Callback callback) {
if (requestCode != appCall.getRequestCode()) {
return false;
}
if (attachmentStore != null) {
attachmentStore.cleanupAttachmentsForCall(context, appCall.getCallId());
}
if (callback != null) {
if (NativeProtocol.isErrorResult(data)) {
Exception error = NativeProtocol.getErrorFromResult(data);
// TODO - data.getExtras() doesn't work for the bucketed protocol.
callback.onError(appCall, error, data.getExtras());
} else {
callback.onComplete(appCall, NativeProtocol.getSuccessResultsFromIntent(data));
}
}
return true;
} | java | {
"resource": ""
} |
q14268 | FacebookDialog.canPresentShareDialog | train | public static boolean canPresentShareDialog(Context context, ShareDialogFeature... features) {
return handleCanPresent(context, EnumSet.of(ShareDialogFeature.SHARE_DIALOG, features));
} | java | {
"resource": ""
} |
q14269 | FacebookDialog.canPresentMessageDialog | train | public static boolean canPresentMessageDialog(Context context, MessageDialogFeature... features) {
return handleCanPresent(context, EnumSet.of(MessageDialogFeature.MESSAGE_DIALOG, features));
} | java | {
"resource": ""
} |
q14270 | FacebookDialog.canPresentOpenGraphActionDialog | train | public static boolean canPresentOpenGraphActionDialog(Context context, OpenGraphActionDialogFeature... features) {
return handleCanPresent(context, EnumSet.of(OpenGraphActionDialogFeature.OG_ACTION_DIALOG, features));
} | java | {
"resource": ""
} |
q14271 | FacebookDialog.canPresentOpenGraphMessageDialog | train | public static boolean canPresentOpenGraphMessageDialog(Context context, OpenGraphMessageDialogFeature... features) {
return handleCanPresent(context, EnumSet.of(OpenGraphMessageDialogFeature.OG_MESSAGE_DIALOG, features));
} | java | {
"resource": ""
} |
q14272 | LocaleBasedEnvironment.reduceVariant | train | private static String reduceVariant(final String variant){
if (isEmpty(variant))
throw new AssertionError("Shouldn't happen, can't reduce non existent variant");
int indexOfUnderscore = variant.lastIndexOf('_');
if (indexOfUnderscore==-1)
return "";
return variant.substring(0, indexOfUnderscore);
} | java | {
"resource": ""
} |
q14273 | TypedIdKey.associate | train | @SuppressWarnings({ "unchecked" })
public static <V> V associate(Associator associator, Serializable id,
V value) {
associator.setAssociated(
new TypedIdKey<V>((Class<V>) value.getClass(), id), value);
return value;
} | java | {
"resource": ""
} |
q14274 | TypedIdKey.put | train | @SuppressWarnings({ "unchecked" })
public static <V> V put(Map<? super TypedIdKey<V>, ? super V> map,
Serializable id, V value) {
map.put(new TypedIdKey<V>((Class<V>) value.getClass(), id), value);
return value;
} | java | {
"resource": ""
} |
q14275 | TypedIdKey.associated | train | public static <V> Optional<V> associated(Associator associator,
Class<V> type, Serializable id) {
return associator.associated(new TypedIdKey<>(type, id), type);
} | java | {
"resource": ""
} |
q14276 | TypedIdKey.get | train | @SuppressWarnings({ "unchecked" })
public static <V> Optional<V> get(Map<?, ?> map, Class<V> type,
Serializable id) {
return Optional
.ofNullable((V) map.get(new TypedIdKey<>(type, id)));
} | java | {
"resource": ""
} |
q14277 | BaseFolder.with | train | public static BaseFolder with(String first, String... more) {
return new BaseFolder(Paths.get(first, more));
} | java | {
"resource": ""
} |
q14278 | GeneratorRegistry.add | train | @SuppressWarnings({ "PMD.GuardLogStatement", "PMD.AvoidDuplicateLiterals" })
public void add(Object obj) {
synchronized (this) {
running += 1;
if (generators != null) {
generators.put(obj, null);
generatorTracking.finest(() -> "Added generator " + obj
+ ", " + generators.size() + " generators registered: "
+ generators.keySet());
}
if (running == 1) { // NOPMD, no, not using a constant for this.
keepAlive = new Thread("GeneratorRegistry") {
@Override
public void run() {
try {
while (true) {
Thread.sleep(Long.MAX_VALUE);
}
} catch (InterruptedException e) {
// Okay, then stop
}
}
};
keepAlive.start();
}
}
} | java | {
"resource": ""
} |
q14279 | GeneratorRegistry.remove | train | @SuppressWarnings("PMD.GuardLogStatement")
public void remove(Object obj) {
synchronized (this) {
running -= 1;
if (generators != null) {
generators.remove(obj);
generatorTracking.finest(() -> "Removed generator " + obj
+ ", " + generators.size() + " generators registered: "
+ generators.keySet());
}
if (running == 0) {
generatorTracking
.finest(() -> "Zero generators, notifying all.");
keepAlive.interrupt();
notifyAll();
}
}
} | java | {
"resource": ""
} |
q14280 | GeneratorRegistry.awaitExhaustion | train | @SuppressWarnings({ "PMD.CollapsibleIfStatements",
"PMD.GuardLogStatement" })
public void awaitExhaustion() throws InterruptedException {
synchronized (this) {
if (generators != null) {
if (running != generators.size()) {
generatorTracking
.severe(() -> "Generator count doesn't match tracked.");
}
}
while (running > 0) {
if (generators != null) {
generatorTracking
.fine(() -> "Thread " + Thread.currentThread().getName()
+ " is waiting, " + generators.size()
+ " generators registered: "
+ generators.keySet());
}
wait();
}
generatorTracking
.finest("Thread " + Thread.currentThread().getName()
+ " continues.");
}
} | java | {
"resource": ""
} |
q14281 | GeneratorRegistry.awaitExhaustion | train | @SuppressWarnings({ "PMD.CollapsibleIfStatements",
"PMD.GuardLogStatement" })
public boolean awaitExhaustion(long timeout)
throws InterruptedException {
synchronized (this) {
if (generators != null) {
if (running != generators.size()) {
generatorTracking.severe(
"Generator count doesn't match tracked.");
}
}
if (isExhausted()) {
return true;
}
if (generators != null) {
generatorTracking
.fine(() -> "Waiting, generators: " + generators.keySet());
}
wait(timeout);
if (generators != null) {
generatorTracking
.fine(() -> "Waited, generators: " + generators.keySet());
}
return isExhausted();
}
} | java | {
"resource": ""
} |
q14282 | TaskSystemInformation.matchesLocale | train | public boolean matchesLocale(String loc) {
return getLocale()==null || (getLocale().isPresent() && getLocale().get().startsWith(loc));
} | java | {
"resource": ""
} |
q14283 | Request.newPostRequest | train | public static Request newPostRequest(Session session, String graphPath, GraphObject graphObject, Callback callback) {
Request request = new Request(session, graphPath, null, HttpMethod.POST , callback);
request.setGraphObject(graphObject);
return request;
} | java | {
"resource": ""
} |
q14284 | Request.newMeRequest | train | public static Request newMeRequest(Session session, final GraphUserCallback callback) {
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(response.getGraphObjectAs(GraphUser.class), response);
}
}
};
return new Request(session, ME, null, null, wrapper);
} | java | {
"resource": ""
} |
q14285 | Request.newMyFriendsRequest | train | public static Request newMyFriendsRequest(Session session, final GraphUserListCallback callback) {
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(typedListFromResponse(response, GraphUser.class), response);
}
}
};
return new Request(session, MY_FRIENDS, null, null, wrapper);
} | java | {
"resource": ""
} |
q14286 | Request.newUploadPhotoRequest | train | public static Request newUploadPhotoRequest(Session session, Bitmap image, Callback callback) {
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, image);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
} | java | {
"resource": ""
} |
q14287 | Request.newUploadPhotoRequest | train | public static Request newUploadPhotoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(PICTURE_PARAM, descriptor);
return new Request(session, MY_PHOTOS, parameters, HttpMethod.POST, callback);
} | java | {
"resource": ""
} |
q14288 | Request.newUploadVideoRequest | train | public static Request newUploadVideoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
return new Request(session, MY_VIDEOS, parameters, HttpMethod.POST, callback);
} | java | {
"resource": ""
} |
q14289 | Request.newGraphPathRequest | train | public static Request newGraphPathRequest(Session session, String graphPath, Callback callback) {
return new Request(session, graphPath, null, null, callback);
} | java | {
"resource": ""
} |
q14290 | Request.newPlacesSearchRequest | train | public static Request newPlacesSearchRequest(Session session, Location location, int radiusInMeters,
int resultsLimit, String searchText, final GraphPlaceListCallback callback) {
if (location == null && Utility.isNullOrEmpty(searchText)) {
throw new FacebookException("Either location or searchText must be specified.");
}
Bundle parameters = new Bundle(5);
parameters.putString("type", "place");
parameters.putInt("limit", resultsLimit);
if (location != null) {
parameters.putString("center",
String.format(Locale.US, "%f,%f", location.getLatitude(), location.getLongitude()));
parameters.putInt("distance", radiusInMeters);
}
if (!Utility.isNullOrEmpty(searchText)) {
parameters.putString("q", searchText);
}
Callback wrapper = new Callback() {
@Override
public void onCompleted(Response response) {
if (callback != null) {
callback.onCompleted(typedListFromResponse(response, GraphPlace.class), response);
}
}
};
return new Request(session, SEARCH, parameters, HttpMethod.GET, wrapper);
} | java | {
"resource": ""
} |
q14291 | Request.newPostOpenGraphActionRequest | train | public static Request newPostOpenGraphActionRequest(Session session, OpenGraphAction openGraphAction,
Callback callback) {
if (openGraphAction == null) {
throw new FacebookException("openGraphAction cannot be null");
}
if (Utility.isNullOrEmpty(openGraphAction.getType())) {
throw new FacebookException("openGraphAction must have non-null 'type' property");
}
String path = String.format(MY_ACTION_FORMAT, openGraphAction.getType());
return newPostRequest(session, path, openGraphAction, callback);
} | java | {
"resource": ""
} |
q14292 | Request.newDeleteObjectRequest | train | public static Request newDeleteObjectRequest(Session session, String id, Callback callback) {
return new Request(session, id, null, HttpMethod.DELETE, callback);
} | java | {
"resource": ""
} |
q14293 | ConfigurationSourceKey.propertyFile | train | public static final ConfigurationSourceKey propertyFile(final String name){
return new ConfigurationSourceKey(Type.FILE, Format.PROPERTIES, name);
} | java | {
"resource": ""
} |
q14294 | ConfigurationSourceKey.xmlFile | train | public static final ConfigurationSourceKey xmlFile(final String name){
return new ConfigurationSourceKey(Type.FILE, Format.XML, name);
} | java | {
"resource": ""
} |
q14295 | ConfigurationSourceKey.jsonFile | train | public static final ConfigurationSourceKey jsonFile(final String name){
return new ConfigurationSourceKey(Type.FILE, Format.JSON, name);
} | java | {
"resource": ""
} |
q14296 | Utility.isSubset | train | public static <T> boolean isSubset(Collection<T> subset, Collection<T> superset) {
if ((superset == null) || (superset.size() == 0)) {
return ((subset == null) || (subset.size() == 0));
}
HashSet<T> hash = new HashSet<T>(superset);
for (T t : subset) {
if (!hash.contains(t)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q14297 | ImageResponseCache.getCachedImageStream | train | static InputStream getCachedImageStream(URI url, Context context) {
InputStream imageStream = null;
if (url != null) {
if (isCDNURL(url)) {
try {
FileLruCache cache = getCache(context);
imageStream = cache.get(url.toString());
} catch (IOException e) {
Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, e.toString());
}
}
}
return imageStream;
} | java | {
"resource": ""
} |
q14298 | DynamicEnvironment.reduceThis | train | public void reduceThis(){
if (elements==null || elements.isEmpty())
throw new AssertionError("Can't reduce this environment");
elements.remove(elements.size()-1);
} | java | {
"resource": ""
} |
q14299 | DynamicEnvironment.parse | train | public static Environment parse(final String s){
if (s==null || s.isEmpty() || s.trim().isEmpty())
return GlobalEnvironment.INSTANCE;
final String[] tokens = StringUtils.tokenize(s, '_');
final DynamicEnvironment env = new DynamicEnvironment();
for (final String t : tokens) {
env.add(t);
}
return env;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.