repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
kpelykh/docker-java | src/main/java/com/kpelykh/docker/client/DockerClient.java | DockerClient.importImage | public ImageCreateResponse importImage(String repository, String tag, InputStream imageStream) throws DockerException {
Preconditions.checkNotNull(repository, "Repository was not specified");
Preconditions.checkNotNull(imageStream, "imageStream was not provided");
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("repo", repository);
params.add("tag", tag);
params.add("fromSrc", "-");
WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params);
try {
LOGGER.trace("POST: {}", webResource);
return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ImageCreateResponse.class, imageStream);
} catch (UniformInterfaceException exception) {
if (exception.getResponse().getStatus() == 500) {
throw new DockerException("Server error.", exception);
} else {
throw new DockerException(exception);
}
}
} | java | public ImageCreateResponse importImage(String repository, String tag, InputStream imageStream) throws DockerException {
Preconditions.checkNotNull(repository, "Repository was not specified");
Preconditions.checkNotNull(imageStream, "imageStream was not provided");
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("repo", repository);
params.add("tag", tag);
params.add("fromSrc", "-");
WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params);
try {
LOGGER.trace("POST: {}", webResource);
return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ImageCreateResponse.class, imageStream);
} catch (UniformInterfaceException exception) {
if (exception.getResponse().getStatus() == 500) {
throw new DockerException("Server error.", exception);
} else {
throw new DockerException(exception);
}
}
} | [
"public",
"ImageCreateResponse",
"importImage",
"(",
"String",
"repository",
",",
"String",
"tag",
",",
"InputStream",
"imageStream",
")",
"throws",
"DockerException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"repository",
",",
"\"Repository was not specified\"",
... | Create an image by importing the given stream of a tar file.
@param repository the repository to import to
@param tag any tag for this image
@param imageStream the InputStream of the tar file
@return an {@link ImageCreateResponse} containing the id of the imported image
@throws DockerException if the import fails for some reason. | [
"Create",
"an",
"image",
"by",
"importing",
"the",
"given",
"stream",
"of",
"a",
"tar",
"file",
"."
] | 26b4069bb1985a8c293a016aaf9b56979771d75b | https://github.com/kpelykh/docker-java/blob/26b4069bb1985a8c293a016aaf9b56979771d75b/src/main/java/com/kpelykh/docker/client/DockerClient.java#L335-L357 | train |
kpelykh/docker-java | src/main/java/com/kpelykh/docker/client/DockerClient.java | DockerClient.removeImage | public void removeImage(String imageId) throws DockerException {
Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty");
try {
WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId)
.queryParam("force", "true");
LOGGER.trace("DELETE: {}", webResource);
webResource.delete();
} catch (UniformInterfaceException exception) {
if (exception.getResponse().getStatus() == 204) {
//no error
LOGGER.trace("Successfully removed image " + imageId);
} else if (exception.getResponse().getStatus() == 404) {
LOGGER.warn("{} no such image", imageId);
} else if (exception.getResponse().getStatus() == 409) {
throw new DockerException("Conflict");
} else if (exception.getResponse().getStatus() == 500) {
throw new DockerException("Server error.", exception);
} else {
throw new DockerException(exception);
}
}
} | java | public void removeImage(String imageId) throws DockerException {
Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty");
try {
WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId)
.queryParam("force", "true");
LOGGER.trace("DELETE: {}", webResource);
webResource.delete();
} catch (UniformInterfaceException exception) {
if (exception.getResponse().getStatus() == 204) {
//no error
LOGGER.trace("Successfully removed image " + imageId);
} else if (exception.getResponse().getStatus() == 404) {
LOGGER.warn("{} no such image", imageId);
} else if (exception.getResponse().getStatus() == 409) {
throw new DockerException("Conflict");
} else if (exception.getResponse().getStatus() == 500) {
throw new DockerException("Server error.", exception);
} else {
throw new DockerException(exception);
}
}
} | [
"public",
"void",
"removeImage",
"(",
"String",
"imageId",
")",
"throws",
"DockerException",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"imageId",
")",
",",
"\"Image ID can't be empty\"",
")",
";",
"try",
"{",
"WebReso... | Remove an image, deleting any tags it might have. | [
"Remove",
"an",
"image",
"deleting",
"any",
"tags",
"it",
"might",
"have",
"."
] | 26b4069bb1985a8c293a016aaf9b56979771d75b | https://github.com/kpelykh/docker-java/blob/26b4069bb1985a8c293a016aaf9b56979771d75b/src/main/java/com/kpelykh/docker/client/DockerClient.java#L377-L400 | train |
HolmesNL/kafka-spout | src/main/java/nl/minvenj/nfi/storm/kafka/KafkaSpout.java | KafkaSpout.fillBuffer | protected boolean fillBuffer() {
if (!_inProgress.isEmpty() || !_queue.isEmpty()) {
throw new IllegalStateException("cannot fill buffer when buffer or pending messages are non-empty");
}
if (_iterator == null) {
// create a stream of messages from _consumer using the streams as defined on construction
final Map<String, List<KafkaStream<byte[], byte[]>>> streams = _consumer.createMessageStreams(Collections.singletonMap(_topic, 1));
_iterator = streams.get(_topic).get(0).iterator();
}
// We'll iterate the stream in a try-clause; kafka stream will poll its client channel for the next message,
// throwing a ConsumerTimeoutException when the configured timeout is exceeded.
try {
int size = 0;
while (size < _bufSize && _iterator.hasNext()) {
final MessageAndMetadata<byte[], byte[]> message = _iterator.next();
final KafkaMessageId id = new KafkaMessageId(message.partition(), message.offset());
_inProgress.put(id, message.message());
size++;
}
}
catch (final InvalidMessageException e) {
LOG.warn(e.getMessage(), e);
}
catch (final ConsumerTimeoutException e) {
// ignore, storm will call nextTuple again at some point in the near future
// timeout does *not* mean that no messages were read (state is checked below)
}
if (_inProgress.size() > 0) {
// set _queue to all currently pending kafka message ids
_queue.addAll(_inProgress.keySet());
LOG.debug("buffer now has {} messages to be emitted", _queue.size());
// message(s) appended to buffer
return true;
}
else {
// no messages appended to buffer
return false;
}
} | java | protected boolean fillBuffer() {
if (!_inProgress.isEmpty() || !_queue.isEmpty()) {
throw new IllegalStateException("cannot fill buffer when buffer or pending messages are non-empty");
}
if (_iterator == null) {
// create a stream of messages from _consumer using the streams as defined on construction
final Map<String, List<KafkaStream<byte[], byte[]>>> streams = _consumer.createMessageStreams(Collections.singletonMap(_topic, 1));
_iterator = streams.get(_topic).get(0).iterator();
}
// We'll iterate the stream in a try-clause; kafka stream will poll its client channel for the next message,
// throwing a ConsumerTimeoutException when the configured timeout is exceeded.
try {
int size = 0;
while (size < _bufSize && _iterator.hasNext()) {
final MessageAndMetadata<byte[], byte[]> message = _iterator.next();
final KafkaMessageId id = new KafkaMessageId(message.partition(), message.offset());
_inProgress.put(id, message.message());
size++;
}
}
catch (final InvalidMessageException e) {
LOG.warn(e.getMessage(), e);
}
catch (final ConsumerTimeoutException e) {
// ignore, storm will call nextTuple again at some point in the near future
// timeout does *not* mean that no messages were read (state is checked below)
}
if (_inProgress.size() > 0) {
// set _queue to all currently pending kafka message ids
_queue.addAll(_inProgress.keySet());
LOG.debug("buffer now has {} messages to be emitted", _queue.size());
// message(s) appended to buffer
return true;
}
else {
// no messages appended to buffer
return false;
}
} | [
"protected",
"boolean",
"fillBuffer",
"(",
")",
"{",
"if",
"(",
"!",
"_inProgress",
".",
"isEmpty",
"(",
")",
"||",
"!",
"_queue",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"cannot fill buffer when buffer or pending mess... | Refills the buffer with messages from the configured kafka topic if available.
@return Whether the buffer contains messages to be emitted after this call.
@throws IllegalStateException When current buffer is not empty or messages not acknowledged by topology. | [
"Refills",
"the",
"buffer",
"with",
"messages",
"from",
"the",
"configured",
"kafka",
"topic",
"if",
"available",
"."
] | bef626b9fab6946a7e0d3c85979ec36ae0870233 | https://github.com/HolmesNL/kafka-spout/blob/bef626b9fab6946a7e0d3c85979ec36ae0870233/src/main/java/nl/minvenj/nfi/storm/kafka/KafkaSpout.java#L185-L226 | train |
HolmesNL/kafka-spout | src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java | ConfigUtils.checkConfigSanity | public static void checkConfigSanity(final Properties config) {
// auto-committing offsets should be disabled
final Object autoCommit = config.getProperty("auto.commit.enable");
if (autoCommit == null || Boolean.parseBoolean(String.valueOf(autoCommit))) {
throw new IllegalArgumentException("kafka configuration 'auto.commit.enable' should be set to false for operation in storm");
}
// consumer timeout should not block calls indefinitely
final Object consumerTimeout = config.getProperty("consumer.timeout.ms");
if (consumerTimeout == null || Integer.parseInt(String.valueOf(consumerTimeout)) < 0) {
throw new IllegalArgumentException("kafka configuration value for 'consumer.timeout.ms' is not suitable for operation in storm");
}
} | java | public static void checkConfigSanity(final Properties config) {
// auto-committing offsets should be disabled
final Object autoCommit = config.getProperty("auto.commit.enable");
if (autoCommit == null || Boolean.parseBoolean(String.valueOf(autoCommit))) {
throw new IllegalArgumentException("kafka configuration 'auto.commit.enable' should be set to false for operation in storm");
}
// consumer timeout should not block calls indefinitely
final Object consumerTimeout = config.getProperty("consumer.timeout.ms");
if (consumerTimeout == null || Integer.parseInt(String.valueOf(consumerTimeout)) < 0) {
throw new IllegalArgumentException("kafka configuration value for 'consumer.timeout.ms' is not suitable for operation in storm");
}
} | [
"public",
"static",
"void",
"checkConfigSanity",
"(",
"final",
"Properties",
"config",
")",
"{",
"// auto-committing offsets should be disabled",
"final",
"Object",
"autoCommit",
"=",
"config",
".",
"getProperty",
"(",
"\"auto.commit.enable\"",
")",
";",
"if",
"(",
"a... | Checks the sanity of a kafka consumer configuration for use in storm.
@param config The configuration parameters to check.
@throws IllegalArgumentException When a sanity check fails. | [
"Checks",
"the",
"sanity",
"of",
"a",
"kafka",
"consumer",
"configuration",
"for",
"use",
"in",
"storm",
"."
] | bef626b9fab6946a7e0d3c85979ec36ae0870233 | https://github.com/HolmesNL/kafka-spout/blob/bef626b9fab6946a7e0d3c85979ec36ae0870233/src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java#L311-L323 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/resource/ClassPathResource.java | ClassPathResource.resolveURL | protected URL resolveURL() {
if (this.clazz != null) {
return this.clazz.getResource(this.path);
}
else if (this.classLoader != null) {
return this.classLoader.getResource(this.path);
}
else {
return ClassLoader.getSystemResource(this.path);
}
} | java | protected URL resolveURL() {
if (this.clazz != null) {
return this.clazz.getResource(this.path);
}
else if (this.classLoader != null) {
return this.classLoader.getResource(this.path);
}
else {
return ClassLoader.getSystemResource(this.path);
}
} | [
"protected",
"URL",
"resolveURL",
"(",
")",
"{",
"if",
"(",
"this",
".",
"clazz",
"!=",
"null",
")",
"{",
"return",
"this",
".",
"clazz",
".",
"getResource",
"(",
"this",
".",
"path",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"classLoader",
"!... | Resolves a URL for the underlying class path resource.
@return the resolved URL, or {@code null} if not resolvable | [
"Resolves",
"a",
"URL",
"for",
"the",
"underlying",
"class",
"path",
"resource",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/resource/ClassPathResource.java#L141-L151 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/resource/ClassPathResource.java | ClassPathResource.getURL | @Override
public URL getURL() throws IOException {
URL url = resolveURL();
if (url == null) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
} | java | @Override
public URL getURL() throws IOException {
URL url = resolveURL();
if (url == null) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
} | [
"@",
"Override",
"public",
"URL",
"getURL",
"(",
")",
"throws",
"IOException",
"{",
"URL",
"url",
"=",
"resolveURL",
"(",
")",
";",
"if",
"(",
"url",
"==",
"null",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"getDescription",
"(",
")",
"+",
... | This implementation returns a URL for the underlying class path resource,
if available.
@see java.lang.ClassLoader#getResource(String)
@see java.lang.Class#getResource(String) | [
"This",
"implementation",
"returns",
"a",
"URL",
"for",
"the",
"underlying",
"class",
"path",
"resource",
"if",
"available",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/resource/ClassPathResource.java#L182-L189 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java | AnnotationUtils.adaptValue | static Object adaptValue(Object value, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
if (classValuesAsString) {
if (value instanceof Class) {
value = ((Class<?>) value).getName();
}
else if (value instanceof Class[]) {
Class<?>[] clazzArray = (Class[]) value;
String[] newValue = new String[clazzArray.length];
for (int i = 0; i < clazzArray.length; i++) {
newValue[i] = clazzArray[i].getName();
}
value = newValue;
}
}
if (nestedAnnotationsAsMap && value instanceof Annotation) {
return getAnnotationAttributes((Annotation) value, classValuesAsString, true);
}
else if (nestedAnnotationsAsMap && value instanceof Annotation[]) {
Annotation[] realAnnotations = (Annotation[]) value;
AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length];
for (int i = 0; i < realAnnotations.length; i++) {
mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], classValuesAsString, true);
}
return mappedAnnotations;
}
else {
return value;
}
} | java | static Object adaptValue(Object value, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
if (classValuesAsString) {
if (value instanceof Class) {
value = ((Class<?>) value).getName();
}
else if (value instanceof Class[]) {
Class<?>[] clazzArray = (Class[]) value;
String[] newValue = new String[clazzArray.length];
for (int i = 0; i < clazzArray.length; i++) {
newValue[i] = clazzArray[i].getName();
}
value = newValue;
}
}
if (nestedAnnotationsAsMap && value instanceof Annotation) {
return getAnnotationAttributes((Annotation) value, classValuesAsString, true);
}
else if (nestedAnnotationsAsMap && value instanceof Annotation[]) {
Annotation[] realAnnotations = (Annotation[]) value;
AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length];
for (int i = 0; i < realAnnotations.length; i++) {
mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], classValuesAsString, true);
}
return mappedAnnotations;
}
else {
return value;
}
} | [
"static",
"Object",
"adaptValue",
"(",
"Object",
"value",
",",
"boolean",
"classValuesAsString",
",",
"boolean",
"nestedAnnotationsAsMap",
")",
"{",
"if",
"(",
"classValuesAsString",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Class",
")",
"{",
"value",
"=",
... | Adapt the given value according to the given class and nested annotation settings.
@param value the annotation attribute value
@param classValuesAsString whether to turn Class references into Strings (for
compatibility with {@link com.freetmp.common.type.AnnotatedTypeMetadata}
or to preserve them as Class references
@param nestedAnnotationsAsMap whether to turn nested Annotation instances into
{@link AnnotationAttributes} maps (for compatibility with
{@link com.freetmp.common.type.AnnotatedTypeMetadata} or to preserve them as
Annotation instances
@return the adapted value, or the original value if no adaptation is needed | [
"Adapt",
"the",
"given",
"value",
"according",
"to",
"the",
"given",
"class",
"and",
"nested",
"annotation",
"settings",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java#L588-L616 | train |
beihaifeiwu/dolphin | xmbg-maven-plugin/src/main/java/com/freetmp/maven/mbg/extend/plugin/MyBatisGeneratorMojo.java | MyBatisGeneratorMojo.extendCG | private void extendCG(Configuration config, List<Context> contexts) {
// just use the extended comment generator
PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType(CommentsWavePlugin.class.getTypeName());
addToContext(contexts, pluginConfiguration);
if (verbose) getLog().info("enable comment wave service");
for (Context context : config.getContexts()) {
context.getCommentGeneratorConfiguration().setConfigurationType(CommentGenerator.class.getTypeName());
if (i18nPath != null && i18nPath.exists()) {
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_I18N_PATH_KEY, i18nPath.getAbsolutePath());
}
if (StringUtils.isEmpty(projectStartYear)) {
projectStartYear = CommentGenerator.XMBG_CG_PROJECT_START_DEFAULT_YEAR;
}
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_PROJECT_START_YEAR, projectStartYear);
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_I18N_LOCALE_KEY, locale);
}
if (verbose) getLog().info("replace the origin comment generator");
} | java | private void extendCG(Configuration config, List<Context> contexts) {
// just use the extended comment generator
PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType(CommentsWavePlugin.class.getTypeName());
addToContext(contexts, pluginConfiguration);
if (verbose) getLog().info("enable comment wave service");
for (Context context : config.getContexts()) {
context.getCommentGeneratorConfiguration().setConfigurationType(CommentGenerator.class.getTypeName());
if (i18nPath != null && i18nPath.exists()) {
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_I18N_PATH_KEY, i18nPath.getAbsolutePath());
}
if (StringUtils.isEmpty(projectStartYear)) {
projectStartYear = CommentGenerator.XMBG_CG_PROJECT_START_DEFAULT_YEAR;
}
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_PROJECT_START_YEAR, projectStartYear);
context.getCommentGeneratorConfiguration().addProperty(CommentGenerator.XMBG_CG_I18N_LOCALE_KEY, locale);
}
if (verbose) getLog().info("replace the origin comment generator");
} | [
"private",
"void",
"extendCG",
"(",
"Configuration",
"config",
",",
"List",
"<",
"Context",
">",
"contexts",
")",
"{",
"// just use the extended comment generator",
"PluginConfiguration",
"pluginConfiguration",
"=",
"new",
"PluginConfiguration",
"(",
")",
";",
"pluginCo... | extend origin mbg the ability for generating comments | [
"extend",
"origin",
"mbg",
"the",
"ability",
"for",
"generating",
"comments"
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/xmbg-maven-plugin/src/main/java/com/freetmp/maven/mbg/extend/plugin/MyBatisGeneratorMojo.java#L392-L413 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/AbstractMerger.java | AbstractMerger.getMerger | public static <T extends Node> AbstractMerger<T> getMerger(Class<T> clazz) {
AbstractMerger<T> merger = null;
Class<?> type = clazz;
while (merger == null && type != null) {
merger = map.get(type);
type = type.getSuperclass();
}
return merger;
} | java | public static <T extends Node> AbstractMerger<T> getMerger(Class<T> clazz) {
AbstractMerger<T> merger = null;
Class<?> type = clazz;
while (merger == null && type != null) {
merger = map.get(type);
type = type.getSuperclass();
}
return merger;
} | [
"public",
"static",
"<",
"T",
"extends",
"Node",
">",
"AbstractMerger",
"<",
"T",
">",
"getMerger",
"(",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"AbstractMerger",
"<",
"T",
">",
"merger",
"=",
"null",
";",
"Class",
"<",
"?",
">",
"type",
"=",
"c... | first check if mapper of the type T exist, if existed return it
else check if mapper of the supper type exist, then return it
@param <T> the generic type which extends from Node
@param clazz The class of type T
@return null if not found else the merger of the type T | [
"first",
"check",
"if",
"mapper",
"of",
"the",
"type",
"T",
"exist",
"if",
"existed",
"return",
"it",
"else",
"check",
"if",
"mapper",
"of",
"the",
"supper",
"type",
"exist",
"then",
"return",
"it"
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/AbstractMerger.java#L336-L348 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/expression/NormalAnnotationExprMerger.java | NormalAnnotationExprMerger.doIsEquals | @Override
public boolean doIsEquals(NormalAnnotationExpr first, NormalAnnotationExpr second) {
boolean equals = true;
if (!first.getName().equals(second.getName())) equals = false;
if (equals == true) {
if (first.getPairs() == null) return second.getPairs() == null;
if (!isSmallerHasEqualsInBigger(first.getPairs(), second.getPairs(), true)) return false;
}
return equals;
} | java | @Override
public boolean doIsEquals(NormalAnnotationExpr first, NormalAnnotationExpr second) {
boolean equals = true;
if (!first.getName().equals(second.getName())) equals = false;
if (equals == true) {
if (first.getPairs() == null) return second.getPairs() == null;
if (!isSmallerHasEqualsInBigger(first.getPairs(), second.getPairs(), true)) return false;
}
return equals;
} | [
"@",
"Override",
"public",
"boolean",
"doIsEquals",
"(",
"NormalAnnotationExpr",
"first",
",",
"NormalAnnotationExpr",
"second",
")",
"{",
"boolean",
"equals",
"=",
"true",
";",
"if",
"(",
"!",
"first",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"second",... | 1. check the name
2. check the member including key and value
if their size is not the same and the less one is all matched in the more one return true | [
"1",
".",
"check",
"the",
"name",
"2",
".",
"check",
"the",
"member",
"including",
"key",
"and",
"value",
"if",
"their",
"size",
"is",
"not",
"the",
"same",
"and",
"the",
"less",
"one",
"is",
"all",
"matched",
"in",
"the",
"more",
"one",
"return",
"t... | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/expression/NormalAnnotationExprMerger.java#L29-L45 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/CompilationUnitMerger.java | CompilationUnitMerger.merge | public static String merge(String first, String second) throws ParseException {
JavaParser.setDoNotAssignCommentsPreceedingEmptyLines(false);
CompilationUnit cu1 = JavaParser.parse(new StringReader(first), true);
CompilationUnit cu2 = JavaParser.parse(new StringReader(second), true);
AbstractMerger<CompilationUnit> merger = AbstractMerger.getMerger(CompilationUnit.class);
CompilationUnit result = merger.merge(cu1, cu2);
return result.toString();
} | java | public static String merge(String first, String second) throws ParseException {
JavaParser.setDoNotAssignCommentsPreceedingEmptyLines(false);
CompilationUnit cu1 = JavaParser.parse(new StringReader(first), true);
CompilationUnit cu2 = JavaParser.parse(new StringReader(second), true);
AbstractMerger<CompilationUnit> merger = AbstractMerger.getMerger(CompilationUnit.class);
CompilationUnit result = merger.merge(cu1, cu2);
return result.toString();
} | [
"public",
"static",
"String",
"merge",
"(",
"String",
"first",
",",
"String",
"second",
")",
"throws",
"ParseException",
"{",
"JavaParser",
".",
"setDoNotAssignCommentsPreceedingEmptyLines",
"(",
"false",
")",
";",
"CompilationUnit",
"cu1",
"=",
"JavaParser",
".",
... | Util method to make source merge more convenient
@param first merge params, specifically for the existing source
@param second merge params, specifically for the new source
@return merged result
@throws ParseException cannot parse the input params | [
"Util",
"method",
"to",
"make",
"source",
"merge",
"more",
"convenient"
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/merge/CompilationUnitMerger.java#L57-L65 | train |
orhanobut/mockwebserverplus | mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/Fixture.java | Fixture.parseFrom | public static Fixture parseFrom(String fileName, Parser parser) {
if (fileName == null) {
throw new NullPointerException("File name should not be null");
}
String path = "fixtures/" + fileName + ".yaml";
InputStream inputStream = openPathAsStream(path);
Fixture result = parser.parse(inputStream);
if (result.body != null && !result.body.startsWith("{")) {
String bodyPath = "fixtures/" + result.body;
try {
result.body = readPathIntoString(bodyPath);
} catch (IOException e) {
throw new IllegalStateException("Error reading body: " + bodyPath, e);
}
}
return result;
} | java | public static Fixture parseFrom(String fileName, Parser parser) {
if (fileName == null) {
throw new NullPointerException("File name should not be null");
}
String path = "fixtures/" + fileName + ".yaml";
InputStream inputStream = openPathAsStream(path);
Fixture result = parser.parse(inputStream);
if (result.body != null && !result.body.startsWith("{")) {
String bodyPath = "fixtures/" + result.body;
try {
result.body = readPathIntoString(bodyPath);
} catch (IOException e) {
throw new IllegalStateException("Error reading body: " + bodyPath, e);
}
}
return result;
} | [
"public",
"static",
"Fixture",
"parseFrom",
"(",
"String",
"fileName",
",",
"Parser",
"parser",
")",
"{",
"if",
"(",
"fileName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"File name should not be null\"",
")",
";",
"}",
"String",
"... | Parse the given filename and returns the Fixture object.
@param fileName filename should not contain extension or relative path. ie: login
@param parser parser is required for parsing operation, it should not be null | [
"Parse",
"the",
"given",
"filename",
"and",
"returns",
"the",
"Fixture",
"object",
"."
] | bb2c5cb4eece98745688ec562486b6bfc5d1b6c7 | https://github.com/orhanobut/mockwebserverplus/blob/bb2c5cb4eece98745688ec562486b6bfc5d1b6c7/mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/Fixture.java#L38-L55 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/core/OrderComparator.java | OrderComparator.withSourceProvider | public Comparator<Object> withSourceProvider(final OrderSourceProvider sourceProvider) {
return new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return doCompare(o1, o2, sourceProvider);
}
};
} | java | public Comparator<Object> withSourceProvider(final OrderSourceProvider sourceProvider) {
return new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return doCompare(o1, o2, sourceProvider);
}
};
} | [
"public",
"Comparator",
"<",
"Object",
">",
"withSourceProvider",
"(",
"final",
"OrderSourceProvider",
"sourceProvider",
")",
"{",
"return",
"new",
"Comparator",
"<",
"Object",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"Object",
"o1... | Build an adapted order comparator with the given soruce provider.
@param sourceProvider the order source provider to use
@return the adapted comparator
@since 4.1 | [
"Build",
"an",
"adapted",
"order",
"comparator",
"with",
"the",
"given",
"soruce",
"provider",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/core/OrderComparator.java#L52-L59 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java | StringHelper.collapse | public static String collapse(String name) {
if (name == null) {
return null;
}
int breakPoint = name.lastIndexOf('.');
if (breakPoint < 0) {
return name;
}
return collapseQualifier(name.substring(0, breakPoint), true) + name.substring(breakPoint); // includes last '.'
} | java | public static String collapse(String name) {
if (name == null) {
return null;
}
int breakPoint = name.lastIndexOf('.');
if (breakPoint < 0) {
return name;
}
return collapseQualifier(name.substring(0, breakPoint), true) + name.substring(breakPoint); // includes last '.'
} | [
"public",
"static",
"String",
"collapse",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"int",
"breakPoint",
"=",
"name",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"breakPoint",
... | Collapses a name. Mainly intended for use with classnames, where an example might serve best to explain.
Imagine you have a class named 'org.hibernate.internal.util.StringHelper'; calling collapse on that
classname will result in 'o.h.u.StringHelper'.
@param name The name to collapse.
@return The collapsed name. | [
"Collapses",
"a",
"name",
".",
"Mainly",
"intended",
"for",
"use",
"with",
"classnames",
"where",
"an",
"example",
"might",
"serve",
"best",
"to",
"explain",
".",
"Imagine",
"you",
"have",
"a",
"class",
"named",
"org",
".",
"hibernate",
".",
"internal",
".... | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java#L232-L241 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java | StringHelper.collapseQualifier | public static String collapseQualifier(String qualifier, boolean includeDots) {
StringTokenizer tokenizer = new StringTokenizer(qualifier, ".");
String collapsed = Character.toString(tokenizer.nextToken().charAt(0));
while (tokenizer.hasMoreTokens()) {
if (includeDots) {
collapsed += '.';
}
collapsed += tokenizer.nextToken().charAt(0);
}
return collapsed;
} | java | public static String collapseQualifier(String qualifier, boolean includeDots) {
StringTokenizer tokenizer = new StringTokenizer(qualifier, ".");
String collapsed = Character.toString(tokenizer.nextToken().charAt(0));
while (tokenizer.hasMoreTokens()) {
if (includeDots) {
collapsed += '.';
}
collapsed += tokenizer.nextToken().charAt(0);
}
return collapsed;
} | [
"public",
"static",
"String",
"collapseQualifier",
"(",
"String",
"qualifier",
",",
"boolean",
"includeDots",
")",
"{",
"StringTokenizer",
"tokenizer",
"=",
"new",
"StringTokenizer",
"(",
"qualifier",
",",
"\".\"",
")",
";",
"String",
"collapsed",
"=",
"Character"... | Given a qualifier, collapse it.
@param qualifier The qualifier to collapse.
@param includeDots Should we include the dots in the collapsed form?
@return The collapsed form. | [
"Given",
"a",
"qualifier",
"collapse",
"it",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java#L250-L260 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java | StringHelper.partiallyUnqualify | public static String partiallyUnqualify(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return name;
}
return name.substring(qualifierBase.length() + 1); // +1 to start after the following '.'
} | java | public static String partiallyUnqualify(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return name;
}
return name.substring(qualifierBase.length() + 1); // +1 to start after the following '.'
} | [
"public",
"static",
"String",
"partiallyUnqualify",
"(",
"String",
"name",
",",
"String",
"qualifierBase",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"!",
"name",
".",
"startsWith",
"(",
"qualifierBase",
")",
")",
"{",
"return",
"name",
";",
"}",
"... | Partially unqualifies a qualified name. For example, with a base of 'org.hibernate' the name
'org.hibernate.internal.util.StringHelper' would become 'util.StringHelper'.
@param name The (potentially) qualified name.
@param qualifierBase The qualifier base.
@return The name itself, or the partially unqualified form if it begins with the qualifier base. | [
"Partially",
"unqualifies",
"a",
"qualified",
"name",
".",
"For",
"example",
"with",
"a",
"base",
"of",
"org",
".",
"hibernate",
"the",
"name",
"org",
".",
"hibernate",
".",
"internal",
".",
"util",
".",
"StringHelper",
"would",
"become",
"util",
".",
"Str... | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java#L270-L275 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java | StringHelper.cleanAlias | private static String cleanAlias(String alias) {
char[] chars = alias.toCharArray();
// short cut check...
if (!Character.isLetter(chars[0])) {
for (int i = 1; i < chars.length; i++) {
// as soon as we encounter our first letter, return the substring
// from that position
if (Character.isLetter(chars[i])) {
return alias.substring(i);
}
}
}
return alias;
} | java | private static String cleanAlias(String alias) {
char[] chars = alias.toCharArray();
// short cut check...
if (!Character.isLetter(chars[0])) {
for (int i = 1; i < chars.length; i++) {
// as soon as we encounter our first letter, return the substring
// from that position
if (Character.isLetter(chars[i])) {
return alias.substring(i);
}
}
}
return alias;
} | [
"private",
"static",
"String",
"cleanAlias",
"(",
"String",
"alias",
")",
"{",
"char",
"[",
"]",
"chars",
"=",
"alias",
".",
"toCharArray",
"(",
")",
";",
"// short cut check...",
"if",
"(",
"!",
"Character",
".",
"isLetter",
"(",
"chars",
"[",
"0",
"]",... | Clean the generated alias by removing any non-alpha characters from the
beginning.
@param alias The generated alias to be cleaned.
@return The cleaned alias, stripped of any leading non-alpha characters. | [
"Clean",
"the",
"generated",
"alias",
"by",
"removing",
"any",
"non",
"-",
"alpha",
"characters",
"from",
"the",
"beginning",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java#L495-L508 | train |
sinetja/jauter | src/main/java/jauter/Router.java | Router.path | public String path(M method, T target, Object... params) {
MethodlessRouter<T> router = (method == null)? anyMethodRouter : routers.get(method);
if (router == null) router = anyMethodRouter;
String ret = router.path(target, params);
if (ret != null) return ret;
return (router == anyMethodRouter)? null : anyMethodRouter.path(target, params);
} | java | public String path(M method, T target, Object... params) {
MethodlessRouter<T> router = (method == null)? anyMethodRouter : routers.get(method);
if (router == null) router = anyMethodRouter;
String ret = router.path(target, params);
if (ret != null) return ret;
return (router == anyMethodRouter)? null : anyMethodRouter.path(target, params);
} | [
"public",
"String",
"path",
"(",
"M",
"method",
",",
"T",
"target",
",",
"Object",
"...",
"params",
")",
"{",
"MethodlessRouter",
"<",
"T",
">",
"router",
"=",
"(",
"method",
"==",
"null",
")",
"?",
"anyMethodRouter",
":",
"routers",
".",
"get",
"(",
... | Reverse routing. | [
"Reverse",
"routing",
"."
] | ae8d97d6e2ddfec6e888b1b375aff8cd69392ec8 | https://github.com/sinetja/jauter/blob/ae8d97d6e2ddfec6e888b1b375aff8cd69392ec8/src/main/java/jauter/Router.java#L102-L110 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/converters/ConvertUtils.java | ConvertUtils.convert | public static <T, P extends Convertable<T>> T convert(P value) throws ParseException {
return value == null ? null : value.convert();
} | java | public static <T, P extends Convertable<T>> T convert(P value) throws ParseException {
return value == null ? null : value.convert();
} | [
"public",
"static",
"<",
"T",
",",
"P",
"extends",
"Convertable",
"<",
"T",
">",
">",
"T",
"convert",
"(",
"P",
"value",
")",
"throws",
"ParseException",
"{",
"return",
"value",
"==",
"null",
"?",
"null",
":",
"value",
".",
"convert",
"(",
")",
";",
... | Converting single item if it is not null. | [
"Converting",
"single",
"item",
"if",
"it",
"is",
"not",
"null",
"."
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/converters/ConvertUtils.java#L21-L23 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/converters/ConvertUtils.java | ConvertUtils.create | public static <IN, OUT> OUT create(IN obj, Creator<IN, OUT> creator) {
return obj == null ? null : creator.create(obj);
} | java | public static <IN, OUT> OUT create(IN obj, Creator<IN, OUT> creator) {
return obj == null ? null : creator.create(obj);
} | [
"public",
"static",
"<",
"IN",
",",
"OUT",
">",
"OUT",
"create",
"(",
"IN",
"obj",
",",
"Creator",
"<",
"IN",
",",
"OUT",
">",
"creator",
")",
"{",
"return",
"obj",
"==",
"null",
"?",
"null",
":",
"creator",
".",
"create",
"(",
"obj",
")",
";",
... | Creates output object using provided creator. Returns null if obj null. | [
"Creates",
"output",
"object",
"using",
"provided",
"creator",
".",
"Returns",
"null",
"if",
"obj",
"null",
"."
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/converters/ConvertUtils.java#L124-L126 | train |
sinetja/jauter | src/main/java/jauter/Routed.java | Routed.instanceFromTarget | public static Object instanceFromTarget(Object target) throws InstantiationException, IllegalAccessException {
if (target == null) return null;
if (target instanceof Class) {
// Create handler from class
Class<?> klass = (Class<?>) target;
return klass.newInstance();
} else {
return target;
}
} | java | public static Object instanceFromTarget(Object target) throws InstantiationException, IllegalAccessException {
if (target == null) return null;
if (target instanceof Class) {
// Create handler from class
Class<?> klass = (Class<?>) target;
return klass.newInstance();
} else {
return target;
}
} | [
"public",
"static",
"Object",
"instanceFromTarget",
"(",
"Object",
"target",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"if",
"(",
"target",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"target",
"instanceof",
"Class",
"... | When target is a class, this method calls "newInstance" on the class.
Otherwise it returns the target as is.
@return null if target is null | [
"When",
"target",
"is",
"a",
"class",
"this",
"method",
"calls",
"newInstance",
"on",
"the",
"class",
".",
"Otherwise",
"it",
"returns",
"the",
"target",
"as",
"is",
"."
] | ae8d97d6e2ddfec6e888b1b375aff8cd69392ec8 | https://github.com/sinetja/jauter/blob/ae8d97d6e2ddfec6e888b1b375aff8cd69392ec8/src/main/java/jauter/Routed.java#L34-L44 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/asm/Type.java | Type.getDescriptor | private void getDescriptor(final StringBuilder sb) {
if (this.buf == null) {
// descriptor is in byte 3 of 'off' for primitive types (buf ==
// null)
sb.append((char) ((off & 0xFF000000) >>> 24));
} else if (sort == OBJECT) {
sb.append('L');
sb.append(this.buf, off, len);
sb.append(';');
} else { // sort == ARRAY || sort == METHOD
sb.append(this.buf, off, len);
}
} | java | private void getDescriptor(final StringBuilder sb) {
if (this.buf == null) {
// descriptor is in byte 3 of 'off' for primitive types (buf ==
// null)
sb.append((char) ((off & 0xFF000000) >>> 24));
} else if (sort == OBJECT) {
sb.append('L');
sb.append(this.buf, off, len);
sb.append(';');
} else { // sort == ARRAY || sort == METHOD
sb.append(this.buf, off, len);
}
} | [
"private",
"void",
"getDescriptor",
"(",
"final",
"StringBuilder",
"sb",
")",
"{",
"if",
"(",
"this",
".",
"buf",
"==",
"null",
")",
"{",
"// descriptor is in byte 3 of 'off' for primitive types (buf ==",
"// null)",
"sb",
".",
"append",
"(",
"(",
"char",
")",
"... | Appends the descriptor corresponding to this Java type to the given
string builder.
@param sb
the string builder to which the descriptor must be appended. | [
"Appends",
"the",
"descriptor",
"corresponding",
"to",
"this",
"Java",
"type",
"to",
"the",
"given",
"string",
"builder",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/asm/Type.java#L663-L675 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/ui/KeyboardHelper.java | KeyboardHelper.showSoftKeyboard | public static void showSoftKeyboard(Context context, View view) {
if (view == null) {
return;
}
final InputMethodManager manager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.requestFocus();
manager.showSoftInput(view, 0);
} | java | public static void showSoftKeyboard(Context context, View view) {
if (view == null) {
return;
}
final InputMethodManager manager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.requestFocus();
manager.showSoftInput(view, 0);
} | [
"public",
"static",
"void",
"showSoftKeyboard",
"(",
"Context",
"context",
",",
"View",
"view",
")",
"{",
"if",
"(",
"view",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"InputMethodManager",
"manager",
"=",
"(",
"InputMethodManager",
")",
"context",... | Shows soft keyboard and requests focus for given view. | [
"Shows",
"soft",
"keyboard",
"and",
"requests",
"focus",
"for",
"given",
"view",
"."
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/ui/KeyboardHelper.java#L49-L58 | train |
orhanobut/mockwebserverplus | mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/MockWebServerPlus.java | MockWebServerPlus.enqueue | public List<MockResponse> enqueue(String... paths) {
if (paths == null) {
return null;
}
List<MockResponse> mockResponseList = new ArrayList<>();
for (String path : paths) {
Fixture fixture = Fixture.parseFrom(path, parser);
MockResponse mockResponse = fixture.toMockResponse();
mockWebServer.enqueue(mockResponse);
mockResponseList.add(mockResponse);
}
return mockResponseList;
} | java | public List<MockResponse> enqueue(String... paths) {
if (paths == null) {
return null;
}
List<MockResponse> mockResponseList = new ArrayList<>();
for (String path : paths) {
Fixture fixture = Fixture.parseFrom(path, parser);
MockResponse mockResponse = fixture.toMockResponse();
mockWebServer.enqueue(mockResponse);
mockResponseList.add(mockResponse);
}
return mockResponseList;
} | [
"public",
"List",
"<",
"MockResponse",
">",
"enqueue",
"(",
"String",
"...",
"paths",
")",
"{",
"if",
"(",
"paths",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"List",
"<",
"MockResponse",
">",
"mockResponseList",
"=",
"new",
"ArrayList",
"<>",
... | Given paths will be parsed to fixtures and added to the queue. Can be multiple | [
"Given",
"paths",
"will",
"be",
"parsed",
"to",
"fixtures",
"and",
"added",
"to",
"the",
"queue",
".",
"Can",
"be",
"multiple"
] | bb2c5cb4eece98745688ec562486b6bfc5d1b6c7 | https://github.com/orhanobut/mockwebserverplus/blob/bb2c5cb4eece98745688ec562486b6bfc5d1b6c7/mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/MockWebServerPlus.java#L39-L51 | train |
orhanobut/mockwebserverplus | mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/MockWebServerPlus.java | MockWebServerPlus.enqueue | public MockResponse enqueue(SocketPolicy socketPolicy) {
MockResponse mockResponse = new MockResponse().setSocketPolicy(socketPolicy);
mockWebServer.enqueue(mockResponse);
return mockResponse;
} | java | public MockResponse enqueue(SocketPolicy socketPolicy) {
MockResponse mockResponse = new MockResponse().setSocketPolicy(socketPolicy);
mockWebServer.enqueue(mockResponse);
return mockResponse;
} | [
"public",
"MockResponse",
"enqueue",
"(",
"SocketPolicy",
"socketPolicy",
")",
"{",
"MockResponse",
"mockResponse",
"=",
"new",
"MockResponse",
"(",
")",
".",
"setSocketPolicy",
"(",
"socketPolicy",
")",
";",
"mockWebServer",
".",
"enqueue",
"(",
"mockResponse",
"... | Given policy will be enqueued as MockResponse | [
"Given",
"policy",
"will",
"be",
"enqueued",
"as",
"MockResponse"
] | bb2c5cb4eece98745688ec562486b6bfc5d1b6c7 | https://github.com/orhanobut/mockwebserverplus/blob/bb2c5cb4eece98745688ec562486b6bfc5d1b6c7/mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/MockWebServerPlus.java#L56-L60 | train |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/type/GenericCollectionTypeResolver.java | GenericCollectionTypeResolver.getMapValueReturnType | public static Class<?> getMapValueReturnType(Method method, int nestingLevel) {
return ResolvableType.forMethodReturnType(method).getNested(nestingLevel).asMap().resolveGeneric(1);
} | java | public static Class<?> getMapValueReturnType(Method method, int nestingLevel) {
return ResolvableType.forMethodReturnType(method).getNested(nestingLevel).asMap().resolveGeneric(1);
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"getMapValueReturnType",
"(",
"Method",
"method",
",",
"int",
"nestingLevel",
")",
"{",
"return",
"ResolvableType",
".",
"forMethodReturnType",
"(",
"method",
")",
".",
"getNested",
"(",
"nestingLevel",
")",
".",
"as... | Determine the generic value type of the given Map return type.
@param method the method to check the return type for
@param nestingLevel the nesting level of the target type
(typically 1; e.g. in case of a List of Lists, 1 would indicate the
nested List, whereas 2 would indicate the element of the nested List)
@return the generic type, or {@code null} if none | [
"Determine",
"the",
"generic",
"value",
"type",
"of",
"the",
"given",
"Map",
"return",
"type",
"."
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/type/GenericCollectionTypeResolver.java#L270-L272 | train |
beihaifeiwu/dolphin | dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/upsert/AbstractUpsertPlugin.java | AbstractUpsertPlugin.addSingleUpsertToSqlMap | protected void addSingleUpsertToSqlMap(Document document, IntrospectedTable introspectedTable) {
XmlElement update = new XmlElement("update");
update.addAttribute(new Attribute("id", UPSERT));
update.addAttribute(new Attribute("parameterType", "map"));
generateSqlMapContent(introspectedTable, update);
document.getRootElement().addElement(update);
} | java | protected void addSingleUpsertToSqlMap(Document document, IntrospectedTable introspectedTable) {
XmlElement update = new XmlElement("update");
update.addAttribute(new Attribute("id", UPSERT));
update.addAttribute(new Attribute("parameterType", "map"));
generateSqlMapContent(introspectedTable, update);
document.getRootElement().addElement(update);
} | [
"protected",
"void",
"addSingleUpsertToSqlMap",
"(",
"Document",
"document",
",",
"IntrospectedTable",
"introspectedTable",
")",
"{",
"XmlElement",
"update",
"=",
"new",
"XmlElement",
"(",
"\"update\"",
")",
";",
"update",
".",
"addAttribute",
"(",
"new",
"Attribute... | add update xml element to mapper.xml for upsert
@param document The generated xml mapper dom
@param introspectedTable The metadata for database table | [
"add",
"update",
"xml",
"element",
"to",
"mapper",
".",
"xml",
"for",
"upsert"
] | b100579cc6986dce5eba5593ebb5fbae7bad9d1a | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/plugin/upsert/AbstractUpsertPlugin.java#L91-L99 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java | Navigate.start | public void start(Intent intent) {
intent = setupIntent(intent);
if (application != null) {
// Extra flag is required when starting from application:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
return; // No transitions, so just return
}
if (activity != null) {
if (requestCode == NO_RESULT_CODE) {
activity.startActivity(intent);
} else {
activity.startActivityForResult(intent, requestCode);
}
} else if (fragment != null) {
if (requestCode == NO_RESULT_CODE) {
fragment.startActivity(intent);
} else {
fragment.startActivityForResult(intent, requestCode);
}
} else if (fragmentSupport != null) {
if (requestCode == NO_RESULT_CODE) {
fragmentSupport.startActivity(intent);
} else {
fragmentSupport.startActivityForResult(intent, requestCode);
}
}
setTransition(false);
} | java | public void start(Intent intent) {
intent = setupIntent(intent);
if (application != null) {
// Extra flag is required when starting from application:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
return; // No transitions, so just return
}
if (activity != null) {
if (requestCode == NO_RESULT_CODE) {
activity.startActivity(intent);
} else {
activity.startActivityForResult(intent, requestCode);
}
} else if (fragment != null) {
if (requestCode == NO_RESULT_CODE) {
fragment.startActivity(intent);
} else {
fragment.startActivityForResult(intent, requestCode);
}
} else if (fragmentSupport != null) {
if (requestCode == NO_RESULT_CODE) {
fragmentSupport.startActivity(intent);
} else {
fragmentSupport.startActivityForResult(intent, requestCode);
}
}
setTransition(false);
} | [
"public",
"void",
"start",
"(",
"Intent",
"intent",
")",
"{",
"intent",
"=",
"setupIntent",
"(",
"intent",
")",
";",
"if",
"(",
"application",
"!=",
"null",
")",
"{",
"// Extra flag is required when starting from application:",
"intent",
".",
"addFlags",
"(",
"I... | Starts activity by intent. | [
"Starts",
"activity",
"by",
"intent",
"."
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java#L151-L182 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java | Navigate.finish | public void finish(int resultCode, Intent data) {
Activity activity = getActivity();
activity.setResult(resultCode, data);
activity.finish();
setTransition(true);
} | java | public void finish(int resultCode, Intent data) {
Activity activity = getActivity();
activity.setResult(resultCode, data);
activity.finish();
setTransition(true);
} | [
"public",
"void",
"finish",
"(",
"int",
"resultCode",
",",
"Intent",
"data",
")",
"{",
"Activity",
"activity",
"=",
"getActivity",
"(",
")",
";",
"activity",
".",
"setResult",
"(",
"resultCode",
",",
"data",
")",
";",
"activity",
".",
"finish",
"(",
")",... | Finishes current activity with provided result code and data. | [
"Finishes",
"current",
"activity",
"with",
"provided",
"result",
"code",
"and",
"data",
"."
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java#L249-L254 | train |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java | Navigate.navigateUp | public void navigateUp(Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
start(intent);
finish();
} | java | public void navigateUp(Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
start(intent);
finish();
} | [
"public",
"void",
"navigateUp",
"(",
"Intent",
"intent",
")",
"{",
"intent",
".",
"setFlags",
"(",
"Intent",
".",
"FLAG_ACTIVITY_CLEAR_TOP",
"|",
"Intent",
".",
"FLAG_ACTIVITY_SINGLE_TOP",
")",
";",
"start",
"(",
"intent",
")",
";",
"finish",
"(",
")",
";",
... | Navigates up to specified activity in the back stack skipping intermediate activities | [
"Navigates",
"up",
"to",
"specified",
"activity",
"in",
"the",
"back",
"stack",
"skipping",
"intermediate",
"activities"
] | aca9f6d5acfc6bd3694984b7f89956e1a0146ddb | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/nav/Navigate.java#L266-L270 | train |
advantageous/konf | src/main/java/io/advantageous/config/ConfigLoader.java | ConfigLoader.load | public static Config load(final String... resources) {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try (final InputStream resourceAsStream = findResource("jjs-config-utils.js")) {
engine.eval(new InputStreamReader(resourceAsStream));
loadResources(engine, resources);
} catch (final ScriptException se) {
throw new IllegalArgumentException("unable to execute main javascript.", se);
} catch (final Exception ex) {
if (ex instanceof IllegalArgumentException) {
throw (IllegalArgumentException) ex;
}
throw new IllegalArgumentException("unable to load main resource ", ex);
}
return loadFromObject(engine.get("config"));
} | java | public static Config load(final String... resources) {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try (final InputStream resourceAsStream = findResource("jjs-config-utils.js")) {
engine.eval(new InputStreamReader(resourceAsStream));
loadResources(engine, resources);
} catch (final ScriptException se) {
throw new IllegalArgumentException("unable to execute main javascript.", se);
} catch (final Exception ex) {
if (ex instanceof IllegalArgumentException) {
throw (IllegalArgumentException) ex;
}
throw new IllegalArgumentException("unable to load main resource ", ex);
}
return loadFromObject(engine.get("config"));
} | [
"public",
"static",
"Config",
"load",
"(",
"final",
"String",
"...",
"resources",
")",
"{",
"final",
"ScriptEngine",
"engine",
"=",
"new",
"ScriptEngineManager",
"(",
")",
".",
"getEngineByName",
"(",
"\"nashorn\"",
")",
";",
"try",
"(",
"final",
"InputStream"... | Loads a config file.
@param resources classpath resources to from which to load javascript
@return Config. | [
"Loads",
"a",
"config",
"file",
"."
] | 51f773fdee0467d8e4b3aaed3567b8b40b5ca9a7 | https://github.com/advantageous/konf/blob/51f773fdee0467d8e4b3aaed3567b8b40b5ca9a7/src/main/java/io/advantageous/config/ConfigLoader.java#L77-L91 | train |
advantageous/konf | src/main/java/io/advantageous/config/ConfigFromObject.java | ConfigFromObject.parseDurationUsingTypeSafeSpec | private Duration parseDurationUsingTypeSafeSpec(final String path, final String durationString) {
/* Check to see if any of the postfixes are at the end of the durationString. */
final Optional<Map.Entry<TimeUnit, List<String>>> entry = timeUnitMap.entrySet().stream()
.filter(timeUnitListEntry ->
/* Go through values in map and see if there are any matches. */
timeUnitListEntry.getValue()
.stream()
.anyMatch(durationString::endsWith))
.findFirst();
/* if we did not match any postFixes then exit early with an exception. */
if (!entry.isPresent()) {
throw new IllegalArgumentException("Path " + path + " does not resolve to a duration " + durationString);
}
/* Convert the value to a Duration.
*/
Optional<Duration> optional = entry.map(timeUnitListEntry -> {
/* Find the prefix that matches the best. Prefixes are ordered by length.
* Biggest prefixes are matched first.
*/
final Optional<String> postFix = timeUnitListEntry
.getValue()
.stream()
.filter(durationString::endsWith)
.findFirst();
if (postFix.isPresent()) {
/* Remove the prefix from the string so only the unit remains. */
final String unitString = durationString.replace(postFix.get(), "").trim();
/* Try to parse the units, if the units do not parse than they gave us a bad prefix. */
try {
long unit = Long.parseLong(unitString);
return Duration.ofNanos(timeUnitListEntry.getKey().toNanos(unit));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
} else {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
});
if (optional.isPresent()) {
return optional.get();
} else {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
} | java | private Duration parseDurationUsingTypeSafeSpec(final String path, final String durationString) {
/* Check to see if any of the postfixes are at the end of the durationString. */
final Optional<Map.Entry<TimeUnit, List<String>>> entry = timeUnitMap.entrySet().stream()
.filter(timeUnitListEntry ->
/* Go through values in map and see if there are any matches. */
timeUnitListEntry.getValue()
.stream()
.anyMatch(durationString::endsWith))
.findFirst();
/* if we did not match any postFixes then exit early with an exception. */
if (!entry.isPresent()) {
throw new IllegalArgumentException("Path " + path + " does not resolve to a duration " + durationString);
}
/* Convert the value to a Duration.
*/
Optional<Duration> optional = entry.map(timeUnitListEntry -> {
/* Find the prefix that matches the best. Prefixes are ordered by length.
* Biggest prefixes are matched first.
*/
final Optional<String> postFix = timeUnitListEntry
.getValue()
.stream()
.filter(durationString::endsWith)
.findFirst();
if (postFix.isPresent()) {
/* Remove the prefix from the string so only the unit remains. */
final String unitString = durationString.replace(postFix.get(), "").trim();
/* Try to parse the units, if the units do not parse than they gave us a bad prefix. */
try {
long unit = Long.parseLong(unitString);
return Duration.ofNanos(timeUnitListEntry.getKey().toNanos(unit));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
} else {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
});
if (optional.isPresent()) {
return optional.get();
} else {
throw new IllegalArgumentException("Path does not resolve to a duration " + durationString);
}
} | [
"private",
"Duration",
"parseDurationUsingTypeSafeSpec",
"(",
"final",
"String",
"path",
",",
"final",
"String",
"durationString",
")",
"{",
"/* Check to see if any of the postfixes are at the end of the durationString. */",
"final",
"Optional",
"<",
"Map",
".",
"Entry",
"<",... | Parses a string into duration type safe spec format if possible.
@param path property path
@param durationString duration string using "10 seconds", "10 days", etc. format from type safe.
@return Duration parsed from typesafe config format. | [
"Parses",
"a",
"string",
"into",
"duration",
"type",
"safe",
"spec",
"format",
"if",
"possible",
"."
] | 51f773fdee0467d8e4b3aaed3567b8b40b5ca9a7 | https://github.com/advantageous/konf/blob/51f773fdee0467d8e4b3aaed3567b8b40b5ca9a7/src/main/java/io/advantageous/config/ConfigFromObject.java#L381-L430 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | IO.lowercaseLines | public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(l));
return true;
}
});
}});
} | java | public static Set<String> lowercaseLines(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.startsWith("#") && !l.isEmpty()) add(toEngLowerCase(l));
return true;
}
});
}});
} | [
"public",
"static",
"Set",
"<",
"String",
">",
"lowercaseLines",
"(",
"final",
"Class",
"<",
"?",
">",
"origin",
",",
"final",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"return",
"ImmutableSet",
".",
"copyOf",
"(",
"new",
"HashSet",
"<",
"St... | Return a Set containing trimmed lowercaseLines read from a file, skipping comments. | [
"Return",
"a",
"Set",
"containing",
"trimmed",
"lowercaseLines",
"read",
"from",
"a",
"file",
"skipping",
"comments",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/util/IO.java#L51-L63 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | IO.lowercaseWordSet | public static ImmutableSet<String> lowercaseWordSet(final Class<?> origin, final String resource,
final boolean eliminatePrepAndConj) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
if (!l.isEmpty() && !l.startsWith("#")) {
for (final String part : SPACES.split(l)) {
if (eliminatePrepAndConj) {
final String wordType = Dictionary.checkup(part);
if (wordType != null && (wordType.startsWith("IN") || wordType.startsWith("CC"))) {
continue;
}
}
// add to the containing HashSet we are currently in the init block of
add(toEngLowerCase(clean(part)));
}
}
return true;
}
});
}});
} | java | public static ImmutableSet<String> lowercaseWordSet(final Class<?> origin, final String resource,
final boolean eliminatePrepAndConj) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
if (!l.isEmpty() && !l.startsWith("#")) {
for (final String part : SPACES.split(l)) {
if (eliminatePrepAndConj) {
final String wordType = Dictionary.checkup(part);
if (wordType != null && (wordType.startsWith("IN") || wordType.startsWith("CC"))) {
continue;
}
}
// add to the containing HashSet we are currently in the init block of
add(toEngLowerCase(clean(part)));
}
}
return true;
}
});
}});
} | [
"public",
"static",
"ImmutableSet",
"<",
"String",
">",
"lowercaseWordSet",
"(",
"final",
"Class",
"<",
"?",
">",
"origin",
",",
"final",
"String",
"resource",
",",
"final",
"boolean",
"eliminatePrepAndConj",
")",
"throws",
"IOException",
"{",
"return",
"Immutab... | Returns a Set containing only single words. | [
"Returns",
"a",
"Set",
"containing",
"only",
"single",
"words",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/util/IO.java#L81-L104 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/IO.java | IO.wordSet | public static ImmutableSet<String> wordSet(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.isEmpty() && !l.startsWith("#")) {
for (final String part : SPACES.split(l)) {
add(clean(part));
}
}
return true;
}
});
}});
} | java | public static ImmutableSet<String> wordSet(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.isEmpty() && !l.startsWith("#")) {
for (final String part : SPACES.split(l)) {
add(clean(part));
}
}
return true;
}
});
}});
} | [
"public",
"static",
"ImmutableSet",
"<",
"String",
">",
"wordSet",
"(",
"final",
"Class",
"<",
"?",
">",
"origin",
",",
"final",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"return",
"ImmutableSet",
".",
"copyOf",
"(",
"new",
"HashSet",
"<",
"... | Return a set containing all non-comment non-empty words. | [
"Return",
"a",
"set",
"containing",
"all",
"non",
"-",
"comment",
"non",
"-",
"empty",
"words",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/util/IO.java#L107-L123 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/classifier/NameClassifier.java | NameClassifier.process | public void process(final NerResultSet resultSet) {
final FeatureMap featureMap = conf.getFeatureMap();
if (conf.tracing) trace = new ArrayList<>();
// store the relationship of _phrases in memory for further use
final Map<Phrase, Set<Phrase>> phraseInMemory = new HashMap<>();
// scoring
for (final List<Phrase> phrasesInSentence : resultSet.phrases) {
// for each sentence
for (final Phrase phrase : phrasesInSentence) {
// for each phrase in the sentence
if (phrase.isDate) continue;
// score the phrase
phrase.score = featureMap.score(phrase);
if (conf.tracing) {
trace.addAll(featureMap.trace);
}
boolean isSubPhrase = false;
for (final Map.Entry<Phrase, Set<Phrase>> inMemoryEntry : phraseInMemory.entrySet()) {
if (phrase.isSubPhraseOf(inMemoryEntry.getKey())) {
inMemoryEntry.getValue().add(phrase);
isSubPhrase = true;
break;
}
}
if (!isSubPhrase || phrase.phrase.size() > 1) {
final Set<Phrase> newSet = new HashSet<>();
newSet.add(phrase);
phraseInMemory.put(phrase, newSet);
}
}
}
// copy the score of _phrases that have relationships
for (final Map.Entry<Phrase, Set<Phrase>> inMemoryPhrase : phraseInMemory.entrySet()) {
final Set<Phrase> aSet = inMemoryPhrase.getValue();
final Map<EntityClass, Double> score = inMemoryPhrase.getKey().score;
for (final Phrase phrase : aSet) {
phrase.classify();
if (EntityClass.UNKNOWN.equals(phrase.phraseType)) {
phrase.score = score;
phrase.classify();
}
}
}
} | java | public void process(final NerResultSet resultSet) {
final FeatureMap featureMap = conf.getFeatureMap();
if (conf.tracing) trace = new ArrayList<>();
// store the relationship of _phrases in memory for further use
final Map<Phrase, Set<Phrase>> phraseInMemory = new HashMap<>();
// scoring
for (final List<Phrase> phrasesInSentence : resultSet.phrases) {
// for each sentence
for (final Phrase phrase : phrasesInSentence) {
// for each phrase in the sentence
if (phrase.isDate) continue;
// score the phrase
phrase.score = featureMap.score(phrase);
if (conf.tracing) {
trace.addAll(featureMap.trace);
}
boolean isSubPhrase = false;
for (final Map.Entry<Phrase, Set<Phrase>> inMemoryEntry : phraseInMemory.entrySet()) {
if (phrase.isSubPhraseOf(inMemoryEntry.getKey())) {
inMemoryEntry.getValue().add(phrase);
isSubPhrase = true;
break;
}
}
if (!isSubPhrase || phrase.phrase.size() > 1) {
final Set<Phrase> newSet = new HashSet<>();
newSet.add(phrase);
phraseInMemory.put(phrase, newSet);
}
}
}
// copy the score of _phrases that have relationships
for (final Map.Entry<Phrase, Set<Phrase>> inMemoryPhrase : phraseInMemory.entrySet()) {
final Set<Phrase> aSet = inMemoryPhrase.getValue();
final Map<EntityClass, Double> score = inMemoryPhrase.getKey().score;
for (final Phrase phrase : aSet) {
phrase.classify();
if (EntityClass.UNKNOWN.equals(phrase.phraseType)) {
phrase.score = score;
phrase.classify();
}
}
}
} | [
"public",
"void",
"process",
"(",
"final",
"NerResultSet",
"resultSet",
")",
"{",
"final",
"FeatureMap",
"featureMap",
"=",
"conf",
".",
"getFeatureMap",
"(",
")",
";",
"if",
"(",
"conf",
".",
"tracing",
")",
"trace",
"=",
"new",
"ArrayList",
"<>",
"(",
... | This method process the whole input result set and gives all _phrases in the set a name type - modifies the data
of the passed in NerResultSet!
@param resultSet set to process - modifies the data of the result set! | [
"This",
"method",
"process",
"the",
"whole",
"input",
"result",
"set",
"and",
"gives",
"all",
"_phrases",
"in",
"the",
"set",
"a",
"name",
"type",
"-",
"modifies",
"the",
"data",
"of",
"the",
"passed",
"in",
"NerResultSet!"
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/classifier/NameClassifier.java#L54-L102 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java | Tokenizer.process | public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence
if (canBreakSentence && equalss(trimmedWord, ".", ";", "?", "!")) {
paragraph.add(currentSentence);
currentSentence = new ArrayList<>();
}
}
}
if (!currentSentence.isEmpty()) paragraph.add(currentSentence);
return paragraph;
} | java | public List<List<Token>> process(final String text) {
final List<List<Token>> paragraph = new ArrayList<>();
currentSentence = new ArrayList<>();
final Tokens tokens = splitText(text);
while (tokens.hasNext()) {
final Token t = tokens.next();
final String trimmedWord = t.text.trim();
// skip spaces
if (trimmedWord.isEmpty()) continue;
if (((mode == WITH_PUNCTUATION) || (mode == WITHOUT_PUNCTUATION && isLetterOrDigit(initChar(t.text))))) {
boolean canBreakSentence = true;
if (t.text.contains("'")) {
wordContainsApostrophe(t);
}
else if (".".equals(trimmedWord)) {
canBreakSentence = wordIsFullStop(t);
}
else if (":".equals(trimmedWord)) {
wordIsColon(tokens, t);
}
else currentSentence.add(t);
// handling the end of a sentence
if (canBreakSentence && equalss(trimmedWord, ".", ";", "?", "!")) {
paragraph.add(currentSentence);
currentSentence = new ArrayList<>();
}
}
}
if (!currentSentence.isEmpty()) paragraph.add(currentSentence);
return paragraph;
} | [
"public",
"List",
"<",
"List",
"<",
"Token",
">",
">",
"process",
"(",
"final",
"String",
"text",
")",
"{",
"final",
"List",
"<",
"List",
"<",
"Token",
">",
">",
"paragraph",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"currentSentence",
"=",
"new"... | Tokenize some text - not thread safe.
@param text tokenize this
@return tokenized text | [
"Tokenize",
"some",
"text",
"-",
"not",
"thread",
"safe",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/util/Tokenizer.java#L76-L111 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java | NameExtractor.detectNameWordInSentenceByPosition | private static boolean detectNameWordInSentenceByPosition(final List<Token> _text, final int _pos) {
boolean isFirstWord = false;
boolean nextWordIsName = false;
if (_pos == 0 || !isLetterOrDigit((_text.get(_pos - 1).text.charAt(0)))) {
isFirstWord = true;
//noinspection SimplifiableIfStatement
if (_text.size() > _pos + 1) {
final String plus1 = _text.get(_pos + 1).text;
nextWordIsName = ("of".equalsIgnoreCase(plus1) || "'s".equalsIgnoreCase(plus1))
? ((_text.size() > (_pos + 2)) && isName(_text.get(_pos + 2).text, false, false))
: isName(plus1, false, false);
}
else nextWordIsName = false;
}
//noinspection UnnecessaryLocalVariable
final boolean isName = isName(_text.get(_pos).text, isFirstWord, nextWordIsName);
/*
String wordType = dict.checkup(Strings.toEngLowerCase(_text.get(_pos));
if (isFirstWord && !isName && wordType != null && wordType.startsWith("JJ")) {
// if the first word is determined not to be a name but it is an adj.,
// and if the second word is a name, we consider the first word to be a name as well.
if (isName(_text.get(_pos + 1), false))
return true;
}
*/
return isName;
} | java | private static boolean detectNameWordInSentenceByPosition(final List<Token> _text, final int _pos) {
boolean isFirstWord = false;
boolean nextWordIsName = false;
if (_pos == 0 || !isLetterOrDigit((_text.get(_pos - 1).text.charAt(0)))) {
isFirstWord = true;
//noinspection SimplifiableIfStatement
if (_text.size() > _pos + 1) {
final String plus1 = _text.get(_pos + 1).text;
nextWordIsName = ("of".equalsIgnoreCase(plus1) || "'s".equalsIgnoreCase(plus1))
? ((_text.size() > (_pos + 2)) && isName(_text.get(_pos + 2).text, false, false))
: isName(plus1, false, false);
}
else nextWordIsName = false;
}
//noinspection UnnecessaryLocalVariable
final boolean isName = isName(_text.get(_pos).text, isFirstWord, nextWordIsName);
/*
String wordType = dict.checkup(Strings.toEngLowerCase(_text.get(_pos));
if (isFirstWord && !isName && wordType != null && wordType.startsWith("JJ")) {
// if the first word is determined not to be a name but it is an adj.,
// and if the second word is a name, we consider the first word to be a name as well.
if (isName(_text.get(_pos + 1), false))
return true;
}
*/
return isName;
} | [
"private",
"static",
"boolean",
"detectNameWordInSentenceByPosition",
"(",
"final",
"List",
"<",
"Token",
">",
"_text",
",",
"final",
"int",
"_pos",
")",
"{",
"boolean",
"isFirstWord",
"=",
"false",
";",
"boolean",
"nextWordIsName",
"=",
"false",
";",
"if",
"(... | Detects if a particular word in a sentence is a name. | [
"Detects",
"if",
"a",
"particular",
"word",
"in",
"a",
"sentence",
"is",
"a",
"name",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java#L195-L223 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java | NameExtractor.isName | private static boolean isName(final String _text, final boolean isFirstWord, final boolean nextWordIsName) {
if (hasManyCaps(_text)) return true;
else if (startsWithCap(_text)) {
if (isFirstWord) {
// if the word is the first word in a sentence and
// ends with -ly (adv) -> consider it not a name
if (_text.endsWith("ly")) return false;
// we need to deal with the first word in the sentence very carefully.
// as we can not tell if the first word is a name by detecting upper case characters.
final String type_original = Dictionary.checkup(_text);
final String type_lowercase = Dictionary.checkup(toEngLowerCase(_text));
if (type_original == null) {
// if the word cannot be found in the dictionary, we consider it as a name entity.
if (type_lowercase == null) return true;
}
else if ("NNP".equals(type_original)) return true;
//noinspection IfMayBeConditional,SimplifiableIfStatement
if (startsWith(type_lowercase, "IN", "CC", "RB", "WRB"/*, "JJ"*/, ".")) return false;
else return nextWordIsName;
}
else return true;
}
else return false;
} | java | private static boolean isName(final String _text, final boolean isFirstWord, final boolean nextWordIsName) {
if (hasManyCaps(_text)) return true;
else if (startsWithCap(_text)) {
if (isFirstWord) {
// if the word is the first word in a sentence and
// ends with -ly (adv) -> consider it not a name
if (_text.endsWith("ly")) return false;
// we need to deal with the first word in the sentence very carefully.
// as we can not tell if the first word is a name by detecting upper case characters.
final String type_original = Dictionary.checkup(_text);
final String type_lowercase = Dictionary.checkup(toEngLowerCase(_text));
if (type_original == null) {
// if the word cannot be found in the dictionary, we consider it as a name entity.
if (type_lowercase == null) return true;
}
else if ("NNP".equals(type_original)) return true;
//noinspection IfMayBeConditional,SimplifiableIfStatement
if (startsWith(type_lowercase, "IN", "CC", "RB", "WRB"/*, "JJ"*/, ".")) return false;
else return nextWordIsName;
}
else return true;
}
else return false;
} | [
"private",
"static",
"boolean",
"isName",
"(",
"final",
"String",
"_text",
",",
"final",
"boolean",
"isFirstWord",
",",
"final",
"boolean",
"nextWordIsName",
")",
"{",
"if",
"(",
"hasManyCaps",
"(",
"_text",
")",
")",
"return",
"true",
";",
"else",
"if",
"... | This method detects a word if it is a potential name word. | [
"This",
"method",
"detects",
"a",
"word",
"if",
"it",
"is",
"a",
"potential",
"name",
"word",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java#L226-L250 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java | NameExtractor.getAttachedPrep | private static void getAttachedPrep(final List<Token> sentenceToken, final List<Phrase> sentencePhrase,
final int index) {
final String prep;
boolean nameSequenceMeetEnd = true;
final Collection<Phrase> phraseSequence = new HashSet<>();
int phrasePtr = index;
Phrase currentNamePhrase = sentencePhrase.get(phrasePtr);
int phrasePtrInSentence;
if (currentNamePhrase.attachedWordMap.get("prep") != null) return;
// we need to find out all the name phrases in a sequence:
// Example: Students who came from China, America and Australia are here.
// in the example above, China, America and Australia are three name phrases all attached to the prep: from.
// first loop, search forward to find all the names before the pointer and the attached prep
while (true) {
currentNamePhrase = sentencePhrase.get(phrasePtr);
phrasePtrInSentence = currentNamePhrase.phrasePosition;
if (phrasePtrInSentence == 0) return;
final String attachedWord = sentenceToken.get(phrasePtrInSentence - 1).text;
// if the attached word is a comma or 'and'/'or', we consider it as a conj.
if (",".equalsIgnoreCase(attachedWord)) {
nameSequenceMeetEnd = false;
phraseSequence.add(currentNamePhrase);
}
else if ("and".equalsIgnoreCase(attachedWord) || "or".equalsIgnoreCase(attachedWord)) {
// meet end
phraseSequence.add(currentNamePhrase);
nameSequenceMeetEnd = true;
}
else if (Dictionary.checkup(toEngLowerCase(attachedWord)) != null && Dictionary
.checkup(toEngLowerCase(attachedWord))
.startsWith("IN")) {
prep = attachedWord;
phraseSequence.add(currentNamePhrase);
break;
}
else {
return;
}
phrasePtr--;
if (phrasePtr < 0) return;
if (sentencePhrase.get(phrasePtr).isDate) return;
if (sentencePhrase.get(phrasePtr).phrasePosition + sentencePhrase.get(phrasePtr).phraseLength + 1
!= phrasePtrInSentence) return;
// method terminates if the phrase before is not next to this phrase. This means the name sequence is broken.
}
phrasePtr = index + 1;
// second loop, search backward to find the names behind the pointer
//noinspection LoopConditionNotUpdatedInsideLoop
while (!nameSequenceMeetEnd) {
if (phrasePtr == sentencePhrase.size()) return;
currentNamePhrase = sentencePhrase.get(phrasePtr);
if (currentNamePhrase.isDate) return;
phrasePtrInSentence = currentNamePhrase.phrasePosition;
if (sentencePhrase.get(phrasePtr - 1).phrasePosition + sentencePhrase.get(phrasePtr - 1).phraseLength + 1
!= currentNamePhrase.phrasePosition) return;
// method terminates if the phrase after is not next to this phrase.
final String attachedWord = sentenceToken.get(phrasePtrInSentence - 1).text;
// if the attached word is a comma or 'and'/'or', we consider it as a conj.
if (",".equalsIgnoreCase(attachedWord)) {
phraseSequence.add(currentNamePhrase);
}
else if ("and".equalsIgnoreCase(attachedWord) || "or".equalsIgnoreCase(attachedWord)) {
// meet end
phraseSequence.add(currentNamePhrase);
break;
}
else {
return;
}
phrasePtr++;
}
// finally, attach the prep with the words in the phraseSequence
for (final Phrase name : phraseSequence) {
name.attachedWordMap.put("prep", prep);
}
} | java | private static void getAttachedPrep(final List<Token> sentenceToken, final List<Phrase> sentencePhrase,
final int index) {
final String prep;
boolean nameSequenceMeetEnd = true;
final Collection<Phrase> phraseSequence = new HashSet<>();
int phrasePtr = index;
Phrase currentNamePhrase = sentencePhrase.get(phrasePtr);
int phrasePtrInSentence;
if (currentNamePhrase.attachedWordMap.get("prep") != null) return;
// we need to find out all the name phrases in a sequence:
// Example: Students who came from China, America and Australia are here.
// in the example above, China, America and Australia are three name phrases all attached to the prep: from.
// first loop, search forward to find all the names before the pointer and the attached prep
while (true) {
currentNamePhrase = sentencePhrase.get(phrasePtr);
phrasePtrInSentence = currentNamePhrase.phrasePosition;
if (phrasePtrInSentence == 0) return;
final String attachedWord = sentenceToken.get(phrasePtrInSentence - 1).text;
// if the attached word is a comma or 'and'/'or', we consider it as a conj.
if (",".equalsIgnoreCase(attachedWord)) {
nameSequenceMeetEnd = false;
phraseSequence.add(currentNamePhrase);
}
else if ("and".equalsIgnoreCase(attachedWord) || "or".equalsIgnoreCase(attachedWord)) {
// meet end
phraseSequence.add(currentNamePhrase);
nameSequenceMeetEnd = true;
}
else if (Dictionary.checkup(toEngLowerCase(attachedWord)) != null && Dictionary
.checkup(toEngLowerCase(attachedWord))
.startsWith("IN")) {
prep = attachedWord;
phraseSequence.add(currentNamePhrase);
break;
}
else {
return;
}
phrasePtr--;
if (phrasePtr < 0) return;
if (sentencePhrase.get(phrasePtr).isDate) return;
if (sentencePhrase.get(phrasePtr).phrasePosition + sentencePhrase.get(phrasePtr).phraseLength + 1
!= phrasePtrInSentence) return;
// method terminates if the phrase before is not next to this phrase. This means the name sequence is broken.
}
phrasePtr = index + 1;
// second loop, search backward to find the names behind the pointer
//noinspection LoopConditionNotUpdatedInsideLoop
while (!nameSequenceMeetEnd) {
if (phrasePtr == sentencePhrase.size()) return;
currentNamePhrase = sentencePhrase.get(phrasePtr);
if (currentNamePhrase.isDate) return;
phrasePtrInSentence = currentNamePhrase.phrasePosition;
if (sentencePhrase.get(phrasePtr - 1).phrasePosition + sentencePhrase.get(phrasePtr - 1).phraseLength + 1
!= currentNamePhrase.phrasePosition) return;
// method terminates if the phrase after is not next to this phrase.
final String attachedWord = sentenceToken.get(phrasePtrInSentence - 1).text;
// if the attached word is a comma or 'and'/'or', we consider it as a conj.
if (",".equalsIgnoreCase(attachedWord)) {
phraseSequence.add(currentNamePhrase);
}
else if ("and".equalsIgnoreCase(attachedWord) || "or".equalsIgnoreCase(attachedWord)) {
// meet end
phraseSequence.add(currentNamePhrase);
break;
}
else {
return;
}
phrasePtr++;
}
// finally, attach the prep with the words in the phraseSequence
for (final Phrase name : phraseSequence) {
name.attachedWordMap.put("prep", prep);
}
} | [
"private",
"static",
"void",
"getAttachedPrep",
"(",
"final",
"List",
"<",
"Token",
">",
"sentenceToken",
",",
"final",
"List",
"<",
"Phrase",
">",
"sentencePhrase",
",",
"final",
"int",
"index",
")",
"{",
"final",
"String",
"prep",
";",
"boolean",
"nameSequ... | This method will find all the attached preps of a phrase. | [
"This",
"method",
"will",
"find",
"all",
"the",
"attached",
"preps",
"of",
"a",
"phrase",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java#L253-L341 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java | NameExtractor.startsWithCap | private static boolean startsWithCap(final String word) {
return !"i".equalsIgnoreCase(word)
&& isAllowedChar(word.charAt(0))
&& isUpperCase(word.charAt(0));
} | java | private static boolean startsWithCap(final String word) {
return !"i".equalsIgnoreCase(word)
&& isAllowedChar(word.charAt(0))
&& isUpperCase(word.charAt(0));
} | [
"private",
"static",
"boolean",
"startsWithCap",
"(",
"final",
"String",
"word",
")",
"{",
"return",
"!",
"\"i\"",
".",
"equalsIgnoreCase",
"(",
"word",
")",
"&&",
"isAllowedChar",
"(",
"word",
".",
"charAt",
"(",
"0",
")",
")",
"&&",
"isUpperCase",
"(",
... | This method detects if the word's first character is in capital size.
@return true if it is; false if it is not. | [
"This",
"method",
"detects",
"if",
"the",
"word",
"s",
"first",
"character",
"is",
"in",
"capital",
"size",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java#L348-L352 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java | NameExtractor.hasManyCaps | private static boolean hasManyCaps(final String word) {
if ("i".equalsIgnoreCase(word)) return false;
int capCharCount = 0;
for (int i = 0; i < word.length(); i++) {
if (isUpperCase(word.charAt(i))) capCharCount++;
if (capCharCount == 2) return true;
}
return false;
} | java | private static boolean hasManyCaps(final String word) {
if ("i".equalsIgnoreCase(word)) return false;
int capCharCount = 0;
for (int i = 0; i < word.length(); i++) {
if (isUpperCase(word.charAt(i))) capCharCount++;
if (capCharCount == 2) return true;
}
return false;
} | [
"private",
"static",
"boolean",
"hasManyCaps",
"(",
"final",
"String",
"word",
")",
"{",
"if",
"(",
"\"i\"",
".",
"equalsIgnoreCase",
"(",
"word",
")",
")",
"return",
"false",
";",
"int",
"capCharCount",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",... | This method detects if the word has more than one character which is capital sized.
@return true if there are more than one character upper cased; return false if less than one character is upper cased. | [
"This",
"method",
"detects",
"if",
"the",
"word",
"has",
"more",
"than",
"one",
"character",
"which",
"is",
"capital",
"sized",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/extractor/NameExtractor.java#L358-L366 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/util/Dictionary.java | Dictionary.isPlural | public static boolean isPlural(final String _word) {
final String word = toEngLowerCase(_word);
// word + s
if (word.endsWith("s")) {
final String wordStub = word.substring(0, word.length() - 1);
if (checkup(wordStub) != null) return true;
}
// word + ed
if (word.endsWith("ed")) {
final String wordStub = word.substring(0, word.length() - 2);
if (checkup(wordStub) != null) return true;
}
// word(-y) + ied
if (word.endsWith("ied")) {
final String wordStub = word.substring(0, word.length() - 3) + "y";
if (checkup(wordStub) != null) return true;
}
return false;
} | java | public static boolean isPlural(final String _word) {
final String word = toEngLowerCase(_word);
// word + s
if (word.endsWith("s")) {
final String wordStub = word.substring(0, word.length() - 1);
if (checkup(wordStub) != null) return true;
}
// word + ed
if (word.endsWith("ed")) {
final String wordStub = word.substring(0, word.length() - 2);
if (checkup(wordStub) != null) return true;
}
// word(-y) + ied
if (word.endsWith("ied")) {
final String wordStub = word.substring(0, word.length() - 3) + "y";
if (checkup(wordStub) != null) return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isPlural",
"(",
"final",
"String",
"_word",
")",
"{",
"final",
"String",
"word",
"=",
"toEngLowerCase",
"(",
"_word",
")",
";",
"// word + s",
"if",
"(",
"word",
".",
"endsWith",
"(",
"\"s\"",
")",
")",
"{",
"final",
"Stri... | This method checks if the word is a plural form. | [
"This",
"method",
"checks",
"if",
"the",
"word",
"is",
"a",
"plural",
"form",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/util/Dictionary.java#L49-L71 | train |
adamyork/wiremock-velocity-transformer | src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java | VelocityResponseTransformer.addHeadersToContext | private void addHeadersToContext(final HttpHeaders headers) {
for (HttpHeader header : headers.all()) {
final String rawKey = header.key();
final String transformedKey = rawKey.replaceAll("-", "");
context.put("requestHeader".concat(transformedKey), header.values()
.toString());
}
} | java | private void addHeadersToContext(final HttpHeaders headers) {
for (HttpHeader header : headers.all()) {
final String rawKey = header.key();
final String transformedKey = rawKey.replaceAll("-", "");
context.put("requestHeader".concat(transformedKey), header.values()
.toString());
}
} | [
"private",
"void",
"addHeadersToContext",
"(",
"final",
"HttpHeaders",
"headers",
")",
"{",
"for",
"(",
"HttpHeader",
"header",
":",
"headers",
".",
"all",
"(",
")",
")",
"{",
"final",
"String",
"rawKey",
"=",
"header",
".",
"key",
"(",
")",
";",
"final"... | Adds the request header information to the Velocity context.
@param headers the request headers | [
"Adds",
"the",
"request",
"header",
"information",
"to",
"the",
"Velocity",
"context",
"."
] | 3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd | https://github.com/adamyork/wiremock-velocity-transformer/blob/3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd/src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java#L121-L128 | train |
adamyork/wiremock-velocity-transformer | src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java | VelocityResponseTransformer.addBodyToContext | private void addBodyToContext(final String body) {
if(!body.isEmpty()) {
final JSONParser parser = new JSONParser();
try {
final JSONObject json = (JSONObject) parser.parse(body);
context.put("requestBody", json);
} catch (final ParseException e) {
e.printStackTrace();
}
}
} | java | private void addBodyToContext(final String body) {
if(!body.isEmpty()) {
final JSONParser parser = new JSONParser();
try {
final JSONObject json = (JSONObject) parser.parse(body);
context.put("requestBody", json);
} catch (final ParseException e) {
e.printStackTrace();
}
}
} | [
"private",
"void",
"addBodyToContext",
"(",
"final",
"String",
"body",
")",
"{",
"if",
"(",
"!",
"body",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"JSONParser",
"parser",
"=",
"new",
"JSONParser",
"(",
")",
";",
"try",
"{",
"final",
"JSONObject",
"j... | Adds the request body to the context if one exists.
@param body the request body | [
"Adds",
"the",
"request",
"body",
"to",
"the",
"context",
"if",
"one",
"exists",
"."
] | 3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd | https://github.com/adamyork/wiremock-velocity-transformer/blob/3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd/src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java#L135-L145 | train |
adamyork/wiremock-velocity-transformer | src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java | VelocityResponseTransformer.getRenderedBody | private String getRenderedBody(final ResponseDefinition response) {
final String templatePath = fileSource.getPath().concat("/" + response.getBodyFileName());
final Template template = Velocity.getTemplate(templatePath);
StringWriter writer = new StringWriter();
template.merge(context, writer);
final String rendered = String.valueOf(writer.getBuffer());
return rendered;
} | java | private String getRenderedBody(final ResponseDefinition response) {
final String templatePath = fileSource.getPath().concat("/" + response.getBodyFileName());
final Template template = Velocity.getTemplate(templatePath);
StringWriter writer = new StringWriter();
template.merge(context, writer);
final String rendered = String.valueOf(writer.getBuffer());
return rendered;
} | [
"private",
"String",
"getRenderedBody",
"(",
"final",
"ResponseDefinition",
"response",
")",
"{",
"final",
"String",
"templatePath",
"=",
"fileSource",
".",
"getPath",
"(",
")",
".",
"concat",
"(",
"\"/\"",
"+",
"response",
".",
"getBodyFileName",
"(",
")",
")... | Renders the velocity template.
@param response the response definition | [
"Renders",
"the",
"velocity",
"template",
"."
] | 3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd | https://github.com/adamyork/wiremock-velocity-transformer/blob/3ec0fd9e6d5b0eb04fc92c79e59c34174a729cfd/src/main/java/com/github/adamyork/wiremock/transformer/VelocityResponseTransformer.java#L152-L159 | train |
NICTA/nicta-ner | conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java | Util.positionClassificationMap | public static Map<Integer, NerClassification> positionClassificationMap(final NerResultSet nerResultSet) {
final Map<Integer, NerClassification> m = new HashMap<>();
for (final List<Phrase> sentence : nerResultSet.phrases) {
for (final Phrase p : sentence) {
final int phraseStartIndex = p.phrase.get(0).startIndex;
for (final Token t : p.phrase) {
final NerClassification clas =
new NerClassification(t.text, p.phraseType, phraseStartIndex, p.score);
final NerClassification replaced = m.put(t.startIndex, clas);
if (replaced != null) {
// since modifying the contents of the map this error should now never happen
System.err.println("########### Error start");
System.err.print(nerResultSet);
throw new IllegalStateException("Tried to add a Token to the position classification map " +
"with startIndex " + t.startIndex + " that is already there!");
}
}
}
}
return m;
} | java | public static Map<Integer, NerClassification> positionClassificationMap(final NerResultSet nerResultSet) {
final Map<Integer, NerClassification> m = new HashMap<>();
for (final List<Phrase> sentence : nerResultSet.phrases) {
for (final Phrase p : sentence) {
final int phraseStartIndex = p.phrase.get(0).startIndex;
for (final Token t : p.phrase) {
final NerClassification clas =
new NerClassification(t.text, p.phraseType, phraseStartIndex, p.score);
final NerClassification replaced = m.put(t.startIndex, clas);
if (replaced != null) {
// since modifying the contents of the map this error should now never happen
System.err.println("########### Error start");
System.err.print(nerResultSet);
throw new IllegalStateException("Tried to add a Token to the position classification map " +
"with startIndex " + t.startIndex + " that is already there!");
}
}
}
}
return m;
} | [
"public",
"static",
"Map",
"<",
"Integer",
",",
"NerClassification",
">",
"positionClassificationMap",
"(",
"final",
"NerResultSet",
"nerResultSet",
")",
"{",
"final",
"Map",
"<",
"Integer",
",",
"NerClassification",
">",
"m",
"=",
"new",
"HashMap",
"<>",
"(",
... | Return a Map of Token startIndex to classification of the Phrase that Token is a part of. | [
"Return",
"a",
"Map",
"of",
"Token",
"startIndex",
"to",
"classification",
"of",
"the",
"Phrase",
"that",
"Token",
"is",
"a",
"part",
"of",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java#L39-L61 | train |
NICTA/nicta-ner | nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java | Feature.generateFeatureByName | public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
throws IllegalArgumentException, IOException {
switch (featureType) {
case "RuledWordFeature":
return new RuledWordFeature(resourceNames, weight);
case "PrepositionContextFeature":
return new PrepositionContextFeature(resourceNames, weight);
case "ExistingPhraseFeature":
return new ExistingPhraseFeature(resourceNames, weight);
case "ExistingCleanPhraseFeature":
return new ExistingCleanPhraseFeature(resourceNames, weight);
case "CaseSensitiveWordLookup":
return new CaseSensitiveWordLookup(resourceNames, weight);
case "CaseInsensitiveWordLookup":
return new CaseInsensitiveWordLookup(resourceNames, weight);
default:
throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
}
} | java | public static Feature generateFeatureByName(final String featureType, final int weight, final List<String> resourceNames)
throws IllegalArgumentException, IOException {
switch (featureType) {
case "RuledWordFeature":
return new RuledWordFeature(resourceNames, weight);
case "PrepositionContextFeature":
return new PrepositionContextFeature(resourceNames, weight);
case "ExistingPhraseFeature":
return new ExistingPhraseFeature(resourceNames, weight);
case "ExistingCleanPhraseFeature":
return new ExistingCleanPhraseFeature(resourceNames, weight);
case "CaseSensitiveWordLookup":
return new CaseSensitiveWordLookup(resourceNames, weight);
case "CaseInsensitiveWordLookup":
return new CaseInsensitiveWordLookup(resourceNames, weight);
default:
throw new IllegalArgumentException("Unknown feature: '" + featureType + "'");
}
} | [
"public",
"static",
"Feature",
"generateFeatureByName",
"(",
"final",
"String",
"featureType",
",",
"final",
"int",
"weight",
",",
"final",
"List",
"<",
"String",
">",
"resourceNames",
")",
"throws",
"IllegalArgumentException",
",",
"IOException",
"{",
"switch",
"... | Factory method create features by name. | [
"Factory",
"method",
"create",
"features",
"by",
"name",
"."
] | c2156a0e299004e586926777a995b7795f35ff1c | https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/nicta-ner/src/main/java/org/t3as/ner/classifier/feature/Feature.java#L48-L66 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/message/BatteryLevel.java | BatteryLevel.getVoltage | public float getVoltage() {
// Range mapping from http://stackoverflow.com/a/7506169/254187
float inMin = 0;
float inMax = 100;
float outMin = (float) 2.0;
float outMax = (float) 3.7;
float x = this.percentage;
return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
} | java | public float getVoltage() {
// Range mapping from http://stackoverflow.com/a/7506169/254187
float inMin = 0;
float inMax = 100;
float outMin = (float) 2.0;
float outMax = (float) 3.7;
float x = this.percentage;
return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
} | [
"public",
"float",
"getVoltage",
"(",
")",
"{",
"// Range mapping from http://stackoverflow.com/a/7506169/254187",
"float",
"inMin",
"=",
"0",
";",
"float",
"inMax",
"=",
"100",
";",
"float",
"outMin",
"=",
"(",
"float",
")",
"2.0",
";",
"float",
"outMax",
"=",
... | Get the battery level in volts.
@return Voltage of battery, 2.0 to 3.7 volts inclusive | [
"Get",
"the",
"battery",
"level",
"in",
"volts",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/message/BatteryLevel.java#L30-L39 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.reset | private void reset() {
setState(OADState.INACTIVE);
currentImage = null;
firmwareBundle = null;
nextBlock = 0;
oadListener = null;
watchdog.stop();
oadApproval.reset();
} | java | private void reset() {
setState(OADState.INACTIVE);
currentImage = null;
firmwareBundle = null;
nextBlock = 0;
oadListener = null;
watchdog.stop();
oadApproval.reset();
} | [
"private",
"void",
"reset",
"(",
")",
"{",
"setState",
"(",
"OADState",
".",
"INACTIVE",
")",
";",
"currentImage",
"=",
"null",
";",
"firmwareBundle",
"=",
"null",
";",
"nextBlock",
"=",
"0",
";",
"oadListener",
"=",
"null",
";",
"watchdog",
".",
"stop",... | Set the state to INACTIVE and clear state variables | [
"Set",
"the",
"state",
"to",
"INACTIVE",
"and",
"clear",
"state",
"variables"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L120-L128 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.reconnect | private void reconnect() {
if(uploadInProgress()) {
setState(OADState.RECONNECTING);
BeanManager.getInstance().startDiscovery();
Log.i(TAG, "Waiting for device to reconnect...");
}
} | java | private void reconnect() {
if(uploadInProgress()) {
setState(OADState.RECONNECTING);
BeanManager.getInstance().startDiscovery();
Log.i(TAG, "Waiting for device to reconnect...");
}
} | [
"private",
"void",
"reconnect",
"(",
")",
"{",
"if",
"(",
"uploadInProgress",
"(",
")",
")",
"{",
"setState",
"(",
"OADState",
".",
"RECONNECTING",
")",
";",
"BeanManager",
".",
"getInstance",
"(",
")",
".",
"startDiscovery",
"(",
")",
";",
"Log",
".",
... | Attempt to reconnect to a Bean that is in the middle of OAD process | [
"Attempt",
"to",
"reconnect",
"to",
"a",
"Bean",
"that",
"is",
"in",
"the",
"middle",
"of",
"OAD",
"process"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L133-L139 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.offerNextImage | private void offerNextImage() {
if (oadState == OADState.OFFERING_IMAGES) {
try {
currentImage = firmwareBundle.getNextImage();
if (currentImage != null) {
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
} catch (OADException e) {
// This gets thrown if the firmware bundle is "exhausted", meaning the Bean
// has rejected all of the images in the bundle
Log.e(TAG, e.getMessage());
fail(BeanError.BEAN_REJECTED_FW);
}
} else {
Log.e(TAG, "Got notification on OAD Identify while in unexpected state: " + oadState);
}
} | java | private void offerNextImage() {
if (oadState == OADState.OFFERING_IMAGES) {
try {
currentImage = firmwareBundle.getNextImage();
if (currentImage != null) {
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
} catch (OADException e) {
// This gets thrown if the firmware bundle is "exhausted", meaning the Bean
// has rejected all of the images in the bundle
Log.e(TAG, e.getMessage());
fail(BeanError.BEAN_REJECTED_FW);
}
} else {
Log.e(TAG, "Got notification on OAD Identify while in unexpected state: " + oadState);
}
} | [
"private",
"void",
"offerNextImage",
"(",
")",
"{",
"if",
"(",
"oadState",
"==",
"OADState",
".",
"OFFERING_IMAGES",
")",
"{",
"try",
"{",
"currentImage",
"=",
"firmwareBundle",
".",
"getNextImage",
"(",
")",
";",
"if",
"(",
"currentImage",
"!=",
"null",
"... | Offer the next image available in the Firmware Bundle | [
"Offer",
"the",
"next",
"image",
"available",
"in",
"the",
"Firmware",
"Bundle"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L144-L161 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.onNotificationBlock | private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int requestedBlock = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
// Check for First block
if (requestedBlock == 0) {
Log.i(TAG, String.format("Image accepted (Name: %s) (Size: %s bytes)",currentImage.name(), currentImage.sizeBytes()));
blockTransferStarted = System.currentTimeMillis() / 1000L;
setState(OADState.BLOCK_XFER);
nextBlock = 0;
}
// Normal BLOCK XFER state logic
while (oadState == OADState.BLOCK_XFER &&
nextBlock <= currentImage.blockCount() - 1 &&
nextBlock < (requestedBlock + MAX_IN_AIR_BLOCKS)) {
// Write the block, tell the OAD Listener
writeToCharacteristic(oadBlock, currentImage.block(nextBlock));
oadListener.progress(UploadProgress.create(nextBlock + 1, currentImage.blockCount()));
nextBlock++;
watchdog.poke();
}
// Check for final block requested, for logging purposes only
if (requestedBlock == currentImage.blockCount() - 1) {
// Calculate throughput
long secondsElapsed = System.currentTimeMillis() / 1000L - blockTransferStarted;
double KBs = 0;
if (secondsElapsed > 0) {
KBs = (double) (currentImage.sizeBytes() / secondsElapsed) / 1000;
}
// Log some stats
Log.i(TAG, String.format("Final OAD Block Requested: %s/%s", nextBlock, currentImage.blockCount()));
Log.i(TAG, String.format("Sent %d blocks in %d seconds (%.2f KB/s)", currentImage.blockCount(), secondsElapsed, KBs));
}
} | java | private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int requestedBlock = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
// Check for First block
if (requestedBlock == 0) {
Log.i(TAG, String.format("Image accepted (Name: %s) (Size: %s bytes)",currentImage.name(), currentImage.sizeBytes()));
blockTransferStarted = System.currentTimeMillis() / 1000L;
setState(OADState.BLOCK_XFER);
nextBlock = 0;
}
// Normal BLOCK XFER state logic
while (oadState == OADState.BLOCK_XFER &&
nextBlock <= currentImage.blockCount() - 1 &&
nextBlock < (requestedBlock + MAX_IN_AIR_BLOCKS)) {
// Write the block, tell the OAD Listener
writeToCharacteristic(oadBlock, currentImage.block(nextBlock));
oadListener.progress(UploadProgress.create(nextBlock + 1, currentImage.blockCount()));
nextBlock++;
watchdog.poke();
}
// Check for final block requested, for logging purposes only
if (requestedBlock == currentImage.blockCount() - 1) {
// Calculate throughput
long secondsElapsed = System.currentTimeMillis() / 1000L - blockTransferStarted;
double KBs = 0;
if (secondsElapsed > 0) {
KBs = (double) (currentImage.sizeBytes() / secondsElapsed) / 1000;
}
// Log some stats
Log.i(TAG, String.format("Final OAD Block Requested: %s/%s", nextBlock, currentImage.blockCount()));
Log.i(TAG, String.format("Sent %d blocks in %d seconds (%.2f KB/s)", currentImage.blockCount(), secondsElapsed, KBs));
}
} | [
"private",
"void",
"onNotificationBlock",
"(",
"BluetoothGattCharacteristic",
"characteristic",
")",
"{",
"int",
"requestedBlock",
"=",
"Convert",
".",
"twoBytesToInt",
"(",
"characteristic",
".",
"getValue",
"(",
")",
",",
"Constants",
".",
"CC2540_BYTE_ORDER",
")",
... | Received a notification on Block characteristic
A notification to this characteristic means the Bean has accepted the most recent
firmware file we have offered, which is stored as `this.currentImage`. It is now
time to start sending blocks of FW to the device.
@param characteristic BLE characteristic with a value equal to the the block number | [
"Received",
"a",
"notification",
"on",
"Block",
"characteristic"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L191-L230 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.setupOAD | private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
fail(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
fail(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
fail(BeanError.MISSING_OAD_BLOCK);
return;
}
} | java | private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
fail(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
fail(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
fail(BeanError.MISSING_OAD_BLOCK);
return;
}
} | [
"private",
"void",
"setupOAD",
"(",
")",
"{",
"BluetoothGattService",
"oadService",
"=",
"mGattClient",
".",
"getService",
"(",
"Constants",
".",
"UUID_OAD_SERVICE",
")",
";",
"if",
"(",
"oadService",
"==",
"null",
")",
"{",
"fail",
"(",
"BeanError",
".",
"M... | Setup BLOCK and IDENTIFY characteristics | [
"Setup",
"BLOCK",
"and",
"IDENTIFY",
"characteristics"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L235-L253 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.setupNotifications | private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful");
} else {
Log.e(TAG, "Error while enabling notifications");
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
} | java | private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful");
} else {
Log.e(TAG, "Error while enabling notifications");
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
} | [
"private",
"void",
"setupNotifications",
"(",
")",
"{",
"Log",
".",
"i",
"(",
"TAG",
",",
"\"Enabling OAD notifications\"",
")",
";",
"boolean",
"oadIdentifyNotifying",
"=",
"enableNotifyForChar",
"(",
"oadIdentify",
")",
";",
"boolean",
"oadBlockNotifying",
"=",
... | Enables notifications for all OAD characteristics. | [
"Enables",
"notifications",
"for",
"all",
"OAD",
"characteristics",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L258-L271 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.enableNotifyForChar | private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean success = true;
// Enable notifications/indications for this characteristic
boolean successEnable = mGattClient.setCharacteristicNotification(characteristic, true);
if (successEnable) {
Log.i(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
success = false;
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Constants.UUID_CLIENT_CHAR_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean successDescriptor = mGattClient.writeDescriptor(descriptor);
if (successDescriptor) {
Log.i(TAG, "Successfully wrote notification descriptor: " + descriptor.getUuid());
} else {
success = false;
Log.e(TAG, "Failed to write notification descriptor: " + descriptor.getUuid());
}
return success;
} | java | private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean success = true;
// Enable notifications/indications for this characteristic
boolean successEnable = mGattClient.setCharacteristicNotification(characteristic, true);
if (successEnable) {
Log.i(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
success = false;
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Constants.UUID_CLIENT_CHAR_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean successDescriptor = mGattClient.writeDescriptor(descriptor);
if (successDescriptor) {
Log.i(TAG, "Successfully wrote notification descriptor: " + descriptor.getUuid());
} else {
success = false;
Log.e(TAG, "Failed to write notification descriptor: " + descriptor.getUuid());
}
return success;
} | [
"private",
"boolean",
"enableNotifyForChar",
"(",
"BluetoothGattCharacteristic",
"characteristic",
")",
"{",
"boolean",
"success",
"=",
"true",
";",
"// Enable notifications/indications for this characteristic",
"boolean",
"successEnable",
"=",
"mGattClient",
".",
"setCharacter... | Enable notifications for a given characteristic.
See <a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification">
the Android docs
</a>
on this subject.
@param characteristic The characteristic to enable notifications for
@return true if notifications were enabled successfully | [
"Enable",
"notifications",
"for",
"a",
"given",
"characteristic",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L284-L309 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.writeToCharacteristic | private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
} | java | private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
} | [
"private",
"boolean",
"writeToCharacteristic",
"(",
"BluetoothGattCharacteristic",
"charc",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"charc",
".",
"setValue",
"(",
"data",
")",
";",
"boolean",
"result",
"=",
"mGattClient",
".",
"writeCharacteristic",
"(",
"charc... | Write to a OAD characteristic
@param charc The characteristic being inspected
@return true if it's the OAD Block characteristic | [
"Write",
"to",
"a",
"OAD",
"characteristic"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L317-L328 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.needsUpdate | private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
} | java | private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
} | [
"private",
"boolean",
"needsUpdate",
"(",
"Long",
"bundleVersion",
",",
"String",
"beanVersion",
")",
"{",
"if",
"(",
"beanVersion",
".",
"contains",
"(",
"\"OAD\"",
")",
")",
"{",
"Log",
".",
"i",
"(",
"TAG",
",",
"\"Bundle version: \"",
"+",
"bundleVersion... | Helper function to determine whether a Bean needs a FW update given a specific Bundle version
@param bundleVersion the version string from the provided firmware bundle
@param beanVersion the version string provided from the Bean Device Information Service
@return boolean value stating whether the Bean needs an update | [
"Helper",
"function",
"to",
"determine",
"whether",
"a",
"Bean",
"needs",
"a",
"FW",
"update",
"given",
"a",
"specific",
"Bundle",
"version"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L337-L358 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.checkFirmwareVersion | private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(OADState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
// Check the Bean version against the Bundle version
boolean updateNeeded = needsUpdate(firmwareBundle.version(), version);
if (updateNeeded && oadApproval.isApproved()) {
// Needs update and client has approved, keep the update going
startOfferingImages();
} else if (updateNeeded && !oadApproval.isApproved()) {
// Needs update but client has not approved, ask for approval
watchdog.pause();
oadListener.updateRequired(true);
} else if (!updateNeeded && !oadApproval.isApproved()){
// Does not need update and the client has never approved. This means
// no update is required, and no firmware update ever occurred
finishNoUpdateOccurred();
oadListener.updateRequired(false);
} else if (!updateNeeded && oadApproval.isApproved()) {
// Does not need update, and the client has approved. This means that
// the firmware process actually took place, and completed
finishUpdateOccurred();
} else {
Log.w(TAG, "Unexpected OAD Condition!");
}
}
});
} | java | private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(OADState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
// Check the Bean version against the Bundle version
boolean updateNeeded = needsUpdate(firmwareBundle.version(), version);
if (updateNeeded && oadApproval.isApproved()) {
// Needs update and client has approved, keep the update going
startOfferingImages();
} else if (updateNeeded && !oadApproval.isApproved()) {
// Needs update but client has not approved, ask for approval
watchdog.pause();
oadListener.updateRequired(true);
} else if (!updateNeeded && !oadApproval.isApproved()){
// Does not need update and the client has never approved. This means
// no update is required, and no firmware update ever occurred
finishNoUpdateOccurred();
oadListener.updateRequired(false);
} else if (!updateNeeded && oadApproval.isApproved()) {
// Does not need update, and the client has approved. This means that
// the firmware process actually took place, and completed
finishUpdateOccurred();
} else {
Log.w(TAG, "Unexpected OAD Condition!");
}
}
});
} | [
"private",
"void",
"checkFirmwareVersion",
"(",
")",
"{",
"Log",
".",
"i",
"(",
"TAG",
",",
"\"Checking Firmware version...\"",
")",
";",
"setState",
"(",
"OADState",
".",
"CHECKING_FW_VERSION",
")",
";",
"mGattClient",
".",
"getDeviceProfile",
"(",
")",
".",
... | Check the Beans FW version to determine if an update is required | [
"Check",
"the",
"Beans",
"FW",
"version",
"to",
"determine",
"if",
"an",
"update",
"is",
"required"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L363-L403 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.fail | private void fail(BeanError error) {
Log.e(TAG, "OAD Error: " + error.toString());
if (uploadInProgress()) {
oadListener.error(error);
reset();
}
} | java | private void fail(BeanError error) {
Log.e(TAG, "OAD Error: " + error.toString());
if (uploadInProgress()) {
oadListener.error(error);
reset();
}
} | [
"private",
"void",
"fail",
"(",
"BeanError",
"error",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"OAD Error: \"",
"+",
"error",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"uploadInProgress",
"(",
")",
")",
"{",
"oadListener",
".",
"error",
"(... | Stop the firmware upload and alert the OADListener
@param error The error to be returned to the user | [
"Stop",
"the",
"firmware",
"upload",
"and",
"alert",
"the",
"OADListener"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L410-L416 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.programWithFirmware | public OADApproval programWithFirmware(final FirmwareBundle bundle, OADListener listener) {
if (!mGattClient.isConnected()) {
listener.error(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure");
// Save state for this firmware procedure
this.oadListener = listener;
this.firmwareBundle = bundle;
watchdog.start(OAD_TIMEOUT_SECONDS, watchdogListener);
checkFirmwareVersion();
return this.oadApproval;
} | java | public OADApproval programWithFirmware(final FirmwareBundle bundle, OADListener listener) {
if (!mGattClient.isConnected()) {
listener.error(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure");
// Save state for this firmware procedure
this.oadListener = listener;
this.firmwareBundle = bundle;
watchdog.start(OAD_TIMEOUT_SECONDS, watchdogListener);
checkFirmwareVersion();
return this.oadApproval;
} | [
"public",
"OADApproval",
"programWithFirmware",
"(",
"final",
"FirmwareBundle",
"bundle",
",",
"OADListener",
"listener",
")",
"{",
"if",
"(",
"!",
"mGattClient",
".",
"isConnected",
"(",
")",
")",
"{",
"listener",
".",
"error",
"(",
"BeanError",
".",
"NOT_CON... | Program the Bean's CC2540 with new firmware.
@param bundle The {@link com.punchthrough.bean.sdk.upload.FirmwareBundle} to be sent
@param listener Listener object to alert client of events/state of the Firmware update process | [
"Program",
"the",
"Bean",
"s",
"CC2540",
"with",
"new",
"firmware",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L508-L524 | train |
comtel2000/jfxvnc | jfxvnc-app/src/main/java/org/jfxvnc/app/persist/SessionContext.java | SessionContext.getBindings | public ObservableMap<String, Property<?>> getBindings() {
if (bindings == null) {
bindings = FXCollections.observableHashMap();
}
return bindings;
} | java | public ObservableMap<String, Property<?>> getBindings() {
if (bindings == null) {
bindings = FXCollections.observableHashMap();
}
return bindings;
} | [
"public",
"ObservableMap",
"<",
"String",
",",
"Property",
"<",
"?",
">",
">",
"getBindings",
"(",
")",
"{",
"if",
"(",
"bindings",
"==",
"null",
")",
"{",
"bindings",
"=",
"FXCollections",
".",
"observableHashMap",
"(",
")",
";",
"}",
"return",
"binding... | session scope bindings
@return | [
"session",
"scope",
"bindings"
] | 981be16c79ed07afdb294a9a65f0e69dcd9ce4b6 | https://github.com/comtel2000/jfxvnc/blob/981be16c79ed07afdb294a9a65f0e69dcd9ce4b6/jfxvnc-app/src/main/java/org/jfxvnc/app/persist/SessionContext.java#L205-L210 | train |
ReactiveX/RxJavaGuava | src/main/java/rx/transformer/GuavaTransformers.java | GuavaTransformers.toImmutableList | public static <T> Observable.Transformer<T,ImmutableList<T>> toImmutableList() {
return new Observable.Transformer<T, ImmutableList<T>>() {
@Override
public Observable<ImmutableList<T>> call(Observable<T> source) {
return source.collect(new Func0<ImmutableList.Builder<T>>() {
@Override
public ImmutableList.Builder<T> call() {
return ImmutableList.builder();
}
}, new Action2<ImmutableList.Builder<T>, T>() {
@Override
public void call(ImmutableList.Builder<T> builder, T t) {
builder.add(t);
}
})
.map(new Func1<ImmutableList.Builder<T>, ImmutableList<T>>() {
@Override
public ImmutableList<T> call(ImmutableList.Builder<T> builder) {
return builder.build();
}
});
}
};
} | java | public static <T> Observable.Transformer<T,ImmutableList<T>> toImmutableList() {
return new Observable.Transformer<T, ImmutableList<T>>() {
@Override
public Observable<ImmutableList<T>> call(Observable<T> source) {
return source.collect(new Func0<ImmutableList.Builder<T>>() {
@Override
public ImmutableList.Builder<T> call() {
return ImmutableList.builder();
}
}, new Action2<ImmutableList.Builder<T>, T>() {
@Override
public void call(ImmutableList.Builder<T> builder, T t) {
builder.add(t);
}
})
.map(new Func1<ImmutableList.Builder<T>, ImmutableList<T>>() {
@Override
public ImmutableList<T> call(ImmutableList.Builder<T> builder) {
return builder.build();
}
});
}
};
} | [
"public",
"static",
"<",
"T",
">",
"Observable",
".",
"Transformer",
"<",
"T",
",",
"ImmutableList",
"<",
"T",
">",
">",
"toImmutableList",
"(",
")",
"{",
"return",
"new",
"Observable",
".",
"Transformer",
"<",
"T",
",",
"ImmutableList",
"<",
"T",
">",
... | Returns a Transformer<T,ImmutableList<T>> that maps an Observable<T> to an Observable<ImmutableList<T>> | [
"Returns",
"a",
"Transformer<",
";",
"T",
"ImmutableList<",
";",
"T>",
";",
">",
"that",
"maps",
"an",
"Observable<",
";",
"T>",
";",
"to",
"an",
"Observable<",
";",
"ImmutableList<",
";",
"T>",
";",
">",
";"
] | bfb5da6e073364a96da23d57f47c6b706fb733aa | https://github.com/ReactiveX/RxJavaGuava/blob/bfb5da6e073364a96da23d57f47c6b706fb733aa/src/main/java/rx/transformer/GuavaTransformers.java#L38-L61 | train |
ReactiveX/RxJavaGuava | src/main/java/rx/transformer/GuavaTransformers.java | GuavaTransformers.toImmutableSet | public static <T> Observable.Transformer<T,ImmutableSet<T>> toImmutableSet() {
return new Observable.Transformer<T, ImmutableSet<T>>() {
@Override
public Observable<ImmutableSet<T>> call(Observable<T> source) {
return source.collect(new Func0<ImmutableSet.Builder<T>>() {
@Override
public ImmutableSet.Builder<T> call() {
return ImmutableSet.builder();
}
}, new Action2<ImmutableSet.Builder<T>, T>() {
@Override
public void call(ImmutableSet.Builder<T> builder, T t) {
builder.add(t);
}
})
.map(new Func1<ImmutableSet.Builder<T>, ImmutableSet<T>>() {
@Override
public ImmutableSet<T> call(ImmutableSet.Builder<T> builder) {
return builder.build();
}
});
}
};
} | java | public static <T> Observable.Transformer<T,ImmutableSet<T>> toImmutableSet() {
return new Observable.Transformer<T, ImmutableSet<T>>() {
@Override
public Observable<ImmutableSet<T>> call(Observable<T> source) {
return source.collect(new Func0<ImmutableSet.Builder<T>>() {
@Override
public ImmutableSet.Builder<T> call() {
return ImmutableSet.builder();
}
}, new Action2<ImmutableSet.Builder<T>, T>() {
@Override
public void call(ImmutableSet.Builder<T> builder, T t) {
builder.add(t);
}
})
.map(new Func1<ImmutableSet.Builder<T>, ImmutableSet<T>>() {
@Override
public ImmutableSet<T> call(ImmutableSet.Builder<T> builder) {
return builder.build();
}
});
}
};
} | [
"public",
"static",
"<",
"T",
">",
"Observable",
".",
"Transformer",
"<",
"T",
",",
"ImmutableSet",
"<",
"T",
">",
">",
"toImmutableSet",
"(",
")",
"{",
"return",
"new",
"Observable",
".",
"Transformer",
"<",
"T",
",",
"ImmutableSet",
"<",
"T",
">",
">... | Returns a Transformer<T,ImmutableSet<T>> that maps an Observable<T> to an Observable<ImmutableSet<T>> | [
"Returns",
"a",
"Transformer<",
";",
"T",
"ImmutableSet<",
";",
"T>",
";",
">",
"that",
"maps",
"an",
"Observable<",
";",
"T>",
";",
"to",
"an",
"Observable<",
";",
"ImmutableSet<",
";",
"T>",
";",
">",
";"
] | bfb5da6e073364a96da23d57f47c6b706fb733aa | https://github.com/ReactiveX/RxJavaGuava/blob/bfb5da6e073364a96da23d57f47c6b706fb733aa/src/main/java/rx/transformer/GuavaTransformers.java#L65-L88 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/strategies/NonstrictReadWriteEntityRegionAccessStrategy.java | NonstrictReadWriteEntityRegionAccessStrategy.update | @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException {
log.debug("region access strategy nonstrict-read-write entity update() {} {}", getInternalRegion().getCacheNamespace(), key);
return false;
} | java | @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException {
log.debug("region access strategy nonstrict-read-write entity update() {} {}", getInternalRegion().getCacheNamespace(), key);
return false;
} | [
"@",
"Override",
"public",
"boolean",
"update",
"(",
"Object",
"key",
",",
"Object",
"value",
",",
"Object",
"currentVersion",
",",
"Object",
"previousVersion",
")",
"throws",
"CacheException",
"{",
"log",
".",
"debug",
"(",
"\"region access strategy nonstrict-read-... | not necessary in nostrict-read-write
@see org.hibernate.cache.spi.access.EntityRegionAccessStrategy | [
"not",
"necessary",
"in",
"nostrict",
"-",
"read",
"-",
"write"
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/strategies/NonstrictReadWriteEntityRegionAccessStrategy.java#L38-L42 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/strategies/NonstrictReadWriteEntityRegionAccessStrategy.java | NonstrictReadWriteEntityRegionAccessStrategy.afterUpdate | @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException {
log.debug("region access strategy nonstrict-read-write entity afterUpdate() {} {}", getInternalRegion().getCacheNamespace(), key);
getInternalRegion().evict(key);
return false;
} | java | @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException {
log.debug("region access strategy nonstrict-read-write entity afterUpdate() {} {}", getInternalRegion().getCacheNamespace(), key);
getInternalRegion().evict(key);
return false;
} | [
"@",
"Override",
"public",
"boolean",
"afterUpdate",
"(",
"Object",
"key",
",",
"Object",
"value",
",",
"Object",
"currentVersion",
",",
"Object",
"previousVersion",
",",
"SoftLock",
"lock",
")",
"throws",
"CacheException",
"{",
"log",
".",
"debug",
"(",
"\"re... | need evict the key, after update.
@see org.hibernate.cache.spi.access.EntityRegionAccessStrategy | [
"need",
"evict",
"the",
"key",
"after",
"update",
"."
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/strategies/NonstrictReadWriteEntityRegionAccessStrategy.java#L49-L54 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.handleMessage | private void handleMessage(byte[] data) {
Buffer buffer = new Buffer();
buffer.write(data);
int type = (buffer.readShort() & 0xffff) & ~(APP_MSG_RESPONSE_BIT);
if (type == BeanMessageID.SERIAL_DATA.getRawValue()) {
beanListener.onSerialMessageReceived(buffer.readByteArray());
} else if (type == BeanMessageID.BT_GET_CONFIG.getRawValue()) {
returnConfig(buffer);
} else if (type == BeanMessageID.CC_TEMP_READ.getRawValue()) {
returnTemperature(buffer);
} else if (type == BeanMessageID.BL_GET_META.getRawValue()) {
returnMetadata(buffer);
} else if (type == BeanMessageID.BT_GET_SCRATCH.getRawValue()) {
returnScratchData(buffer);
} else if (type == BeanMessageID.CC_LED_READ_ALL.getRawValue()) {
returnLed(buffer);
} else if (type == BeanMessageID.CC_ACCEL_READ.getRawValue()) {
returnAcceleration(buffer);
} else if (type == BeanMessageID.CC_ACCEL_GET_RANGE.getRawValue()) {
returnAccelerometerRange(buffer);
// Ignore CC_LED_WRITE; it appears to be only an ack
} else if (type == BeanMessageID.CC_GET_AR_POWER.getRawValue()) {
returnArduinoPowerState(buffer);
} else if (type == BeanMessageID.BL_STATUS.getRawValue()) {
try {
Status status = Status.fromPayload(buffer);
handleStatus(status);
} catch (NoEnumFoundException e) {
Log.e(TAG, "Unable to parse status from buffer: " + buffer.toString());
e.printStackTrace();
}
} else {
String fourDigitHex = Integer.toHexString(type);
while (fourDigitHex.length() < 4) {
fourDigitHex = "0" + fourDigitHex;
}
Log.e(TAG, "Received message of unknown type 0x" + fourDigitHex);
returnError(BeanError.UNKNOWN_MESSAGE_ID);
}
} | java | private void handleMessage(byte[] data) {
Buffer buffer = new Buffer();
buffer.write(data);
int type = (buffer.readShort() & 0xffff) & ~(APP_MSG_RESPONSE_BIT);
if (type == BeanMessageID.SERIAL_DATA.getRawValue()) {
beanListener.onSerialMessageReceived(buffer.readByteArray());
} else if (type == BeanMessageID.BT_GET_CONFIG.getRawValue()) {
returnConfig(buffer);
} else if (type == BeanMessageID.CC_TEMP_READ.getRawValue()) {
returnTemperature(buffer);
} else if (type == BeanMessageID.BL_GET_META.getRawValue()) {
returnMetadata(buffer);
} else if (type == BeanMessageID.BT_GET_SCRATCH.getRawValue()) {
returnScratchData(buffer);
} else if (type == BeanMessageID.CC_LED_READ_ALL.getRawValue()) {
returnLed(buffer);
} else if (type == BeanMessageID.CC_ACCEL_READ.getRawValue()) {
returnAcceleration(buffer);
} else if (type == BeanMessageID.CC_ACCEL_GET_RANGE.getRawValue()) {
returnAccelerometerRange(buffer);
// Ignore CC_LED_WRITE; it appears to be only an ack
} else if (type == BeanMessageID.CC_GET_AR_POWER.getRawValue()) {
returnArduinoPowerState(buffer);
} else if (type == BeanMessageID.BL_STATUS.getRawValue()) {
try {
Status status = Status.fromPayload(buffer);
handleStatus(status);
} catch (NoEnumFoundException e) {
Log.e(TAG, "Unable to parse status from buffer: " + buffer.toString());
e.printStackTrace();
}
} else {
String fourDigitHex = Integer.toHexString(type);
while (fourDigitHex.length() < 4) {
fourDigitHex = "0" + fourDigitHex;
}
Log.e(TAG, "Received message of unknown type 0x" + fourDigitHex);
returnError(BeanError.UNKNOWN_MESSAGE_ID);
}
} | [
"private",
"void",
"handleMessage",
"(",
"byte",
"[",
"]",
"data",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"write",
"(",
"data",
")",
";",
"int",
"type",
"=",
"(",
"buffer",
".",
"readShort",
"(",
")",
"&",... | Handles incoming messages from the Bean and dispatches them to the proper handlers.
@param data The raw byte data received from the Bean | [
"Handles",
"incoming",
"messages",
"from",
"the",
"Bean",
"and",
"dispatches",
"them",
"to",
"the",
"proper",
"handlers",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L390-L444 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.handleStatus | private void handleStatus(Status status) {
Log.d(TAG, "Handling Bean status: " + status);
BeanState beanState = status.beanState();
if (beanState == BeanState.READY) {
resetSketchStateTimeout();
if (sketchUploadState == SketchUploadState.SENDING_START_COMMAND) {
sketchUploadState = SketchUploadState.SENDING_BLOCKS;
stopSketchStateTimeout();
sendNextSketchBlock();
}
} else if (beanState == BeanState.PROGRAMMING) {
resetSketchStateTimeout();
} else if (beanState == BeanState.COMPLETE) {
if (onSketchUploadComplete != null) onSketchUploadComplete.run();
resetSketchUploadState();
} else if (beanState == BeanState.ERROR) {
returnUploadError(BeanError.UNKNOWN);
resetSketchUploadState();
}
} | java | private void handleStatus(Status status) {
Log.d(TAG, "Handling Bean status: " + status);
BeanState beanState = status.beanState();
if (beanState == BeanState.READY) {
resetSketchStateTimeout();
if (sketchUploadState == SketchUploadState.SENDING_START_COMMAND) {
sketchUploadState = SketchUploadState.SENDING_BLOCKS;
stopSketchStateTimeout();
sendNextSketchBlock();
}
} else if (beanState == BeanState.PROGRAMMING) {
resetSketchStateTimeout();
} else if (beanState == BeanState.COMPLETE) {
if (onSketchUploadComplete != null) onSketchUploadComplete.run();
resetSketchUploadState();
} else if (beanState == BeanState.ERROR) {
returnUploadError(BeanError.UNKNOWN);
resetSketchUploadState();
}
} | [
"private",
"void",
"handleStatus",
"(",
"Status",
"status",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"Handling Bean status: \"",
"+",
"status",
")",
";",
"BeanState",
"beanState",
"=",
"status",
".",
"beanState",
"(",
")",
";",
"if",
"(",
"beanState",... | Fired when the Bean sends a Status message. Updates the client's internal state machine,
used for uploading sketches and firmware to the Bean.
@param status The status received from the Bean | [
"Fired",
"when",
"the",
"Bean",
"sends",
"a",
"Status",
"message",
".",
"Updates",
"the",
"client",
"s",
"internal",
"state",
"machine",
"used",
"for",
"uploading",
"sketches",
"and",
"firmware",
"to",
"the",
"Bean",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L452-L481 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.resetSketchStateTimeout | private void resetSketchStateTimeout() {
TimerTask onTimeout = new TimerTask() {
@Override
public void run() {
returnUploadError(BeanError.STATE_TIMEOUT);
}
};
stopSketchStateTimeout();
sketchStateTimeout = new Timer();
sketchStateTimeout.schedule(onTimeout, SKETCH_UPLOAD_STATE_TIMEOUT);
} | java | private void resetSketchStateTimeout() {
TimerTask onTimeout = new TimerTask() {
@Override
public void run() {
returnUploadError(BeanError.STATE_TIMEOUT);
}
};
stopSketchStateTimeout();
sketchStateTimeout = new Timer();
sketchStateTimeout.schedule(onTimeout, SKETCH_UPLOAD_STATE_TIMEOUT);
} | [
"private",
"void",
"resetSketchStateTimeout",
"(",
")",
"{",
"TimerTask",
"onTimeout",
"=",
"new",
"TimerTask",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"returnUploadError",
"(",
"BeanError",
".",
"STATE_TIMEOUT",
")",
";",
"}"... | Reset the state timeout timer. If this timer fires, the client has waited too long for a
state update from the Bean and an error will be fired. | [
"Reset",
"the",
"state",
"timeout",
"timer",
".",
"If",
"this",
"timer",
"fires",
"the",
"client",
"has",
"waited",
"too",
"long",
"for",
"a",
"state",
"update",
"from",
"the",
"Bean",
"and",
"an",
"error",
"will",
"be",
"fired",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L507-L518 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.resetSketchBlockSendTimeout | private void resetSketchBlockSendTimeout() {
TimerTask onTimeout = new TimerTask() {
@Override
public void run() {
sendNextSketchBlock();
}
};
stopSketchBlockSendTimeout();
sketchBlockSendTimeout = new Timer();
sketchBlockSendTimeout.schedule(onTimeout, SKETCH_BLOCK_SEND_INTERVAL);
} | java | private void resetSketchBlockSendTimeout() {
TimerTask onTimeout = new TimerTask() {
@Override
public void run() {
sendNextSketchBlock();
}
};
stopSketchBlockSendTimeout();
sketchBlockSendTimeout = new Timer();
sketchBlockSendTimeout.schedule(onTimeout, SKETCH_BLOCK_SEND_INTERVAL);
} | [
"private",
"void",
"resetSketchBlockSendTimeout",
"(",
")",
"{",
"TimerTask",
"onTimeout",
"=",
"new",
"TimerTask",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"sendNextSketchBlock",
"(",
")",
";",
"}",
"}",
";",
"stopSketchBlockS... | Reset the block send timer. When this timer fires, another sketch block is sent. | [
"Reset",
"the",
"block",
"send",
"timer",
".",
"When",
"this",
"timer",
"fires",
"another",
"sketch",
"block",
"is",
"sent",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L523-L534 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.sendNextSketchBlock | private void sendNextSketchBlock() {
byte[] rawBlock = sketchBlocksToSend.get(currSketchBlockNum);
Buffer block = new Buffer();
block.write(rawBlock);
sendMessage(BeanMessageID.BL_FW_BLOCK, block);
resetSketchBlockSendTimeout();
int blocksSent = currSketchBlockNum + 1;
int totalBlocks = sketchBlocksToSend.size();
onSketchUploadProgress.onResult(UploadProgress.create(blocksSent, totalBlocks));
currSketchBlockNum++;
if ( currSketchBlockNum >= sketchBlocksToSend.size() ) {
resetSketchUploadState();
}
} | java | private void sendNextSketchBlock() {
byte[] rawBlock = sketchBlocksToSend.get(currSketchBlockNum);
Buffer block = new Buffer();
block.write(rawBlock);
sendMessage(BeanMessageID.BL_FW_BLOCK, block);
resetSketchBlockSendTimeout();
int blocksSent = currSketchBlockNum + 1;
int totalBlocks = sketchBlocksToSend.size();
onSketchUploadProgress.onResult(UploadProgress.create(blocksSent, totalBlocks));
currSketchBlockNum++;
if ( currSketchBlockNum >= sketchBlocksToSend.size() ) {
resetSketchUploadState();
}
} | [
"private",
"void",
"sendNextSketchBlock",
"(",
")",
"{",
"byte",
"[",
"]",
"rawBlock",
"=",
"sketchBlocksToSend",
".",
"get",
"(",
"currSketchBlockNum",
")",
";",
"Buffer",
"block",
"=",
"new",
"Buffer",
"(",
")",
";",
"block",
".",
"write",
"(",
"rawBlock... | Send one block of sketch data to the Bean and increment the block counter. | [
"Send",
"one",
"block",
"of",
"sketch",
"data",
"to",
"the",
"Bean",
"and",
"increment",
"the",
"block",
"counter",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L539-L555 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.addCallback | private void addCallback(BeanMessageID type, Callback<?> callback) {
List<Callback<?>> callbacks = beanCallbacks.get(type);
if (callbacks == null) {
callbacks = new ArrayList<>(16);
beanCallbacks.put(type, callbacks);
}
callbacks.add(callback);
} | java | private void addCallback(BeanMessageID type, Callback<?> callback) {
List<Callback<?>> callbacks = beanCallbacks.get(type);
if (callbacks == null) {
callbacks = new ArrayList<>(16);
beanCallbacks.put(type, callbacks);
}
callbacks.add(callback);
} | [
"private",
"void",
"addCallback",
"(",
"BeanMessageID",
"type",
",",
"Callback",
"<",
"?",
">",
"callback",
")",
"{",
"List",
"<",
"Callback",
"<",
"?",
">",
">",
"callbacks",
"=",
"beanCallbacks",
".",
"get",
"(",
"type",
")",
";",
"if",
"(",
"callbac... | Add a callback for a Bean message type.
@param type The {@link com.punchthrough.bean.sdk.internal.BeanMessageID} the callback
will answer to
@param callback The callback to store | [
"Add",
"a",
"callback",
"for",
"a",
"Bean",
"message",
"type",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L684-L691 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.getFirstCallback | @SuppressWarnings("unchecked")
private <T> Callback<T> getFirstCallback(BeanMessageID type) {
List<Callback<?>> callbacks = beanCallbacks.get(type);
if (callbacks == null || callbacks.isEmpty()) {
Log.w(TAG, "Got response without callback!");
return null;
}
return (Callback<T>) callbacks.remove(0);
} | java | @SuppressWarnings("unchecked")
private <T> Callback<T> getFirstCallback(BeanMessageID type) {
List<Callback<?>> callbacks = beanCallbacks.get(type);
if (callbacks == null || callbacks.isEmpty()) {
Log.w(TAG, "Got response without callback!");
return null;
}
return (Callback<T>) callbacks.remove(0);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"<",
"T",
">",
"Callback",
"<",
"T",
">",
"getFirstCallback",
"(",
"BeanMessageID",
"type",
")",
"{",
"List",
"<",
"Callback",
"<",
"?",
">",
">",
"callbacks",
"=",
"beanCallbacks",
".",
"get",... | Get the first callback for a Bean message type.
@param type The {@link com.punchthrough.bean.sdk.internal.BeanMessageID} for which to find
an associated callback
@param <T> The parameter type for the callback
@return The callback for the given message type, or null if none exists | [
"Get",
"the",
"first",
"callback",
"for",
"a",
"Bean",
"message",
"type",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L701-L709 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.connect | public void connect(Context context, BeanListener listener) {
lastKnownContext = context;
beanListener = listener;
gattClient.connect(context, device);
} | java | public void connect(Context context, BeanListener listener) {
lastKnownContext = context;
beanListener = listener;
gattClient.connect(context, device);
} | [
"public",
"void",
"connect",
"(",
"Context",
"context",
",",
"BeanListener",
"listener",
")",
"{",
"lastKnownContext",
"=",
"context",
";",
"beanListener",
"=",
"listener",
";",
"gattClient",
".",
"connect",
"(",
"context",
",",
"device",
")",
";",
"}"
] | Attempt to connect to this Bean.
@param context the Android Context used for connection, usually the current activity
@param listener the Bean listener | [
"Attempt",
"to",
"connect",
"to",
"this",
"Bean",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L779-L783 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setLed | public void setLed(LedColor color) {
Buffer buffer = new Buffer();
buffer.writeByte(color.red());
buffer.writeByte(color.green());
buffer.writeByte(color.blue());
sendMessage(BeanMessageID.CC_LED_WRITE_ALL, buffer);
} | java | public void setLed(LedColor color) {
Buffer buffer = new Buffer();
buffer.writeByte(color.red());
buffer.writeByte(color.green());
buffer.writeByte(color.blue());
sendMessage(BeanMessageID.CC_LED_WRITE_ALL, buffer);
} | [
"public",
"void",
"setLed",
"(",
"LedColor",
"color",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeByte",
"(",
"color",
".",
"red",
"(",
")",
")",
";",
"buffer",
".",
"writeByte",
"(",
"color",
".",
"green",... | Set the LED color.
@param color The {@link com.punchthrough.bean.sdk.message.LedColor} being sent to the LED | [
"Set",
"the",
"LED",
"color",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L823-L829 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readLed | public void readLed(Callback<LedColor> callback) {
addCallback(BeanMessageID.CC_LED_READ_ALL, callback);
sendMessageWithoutPayload(BeanMessageID.CC_LED_READ_ALL);
} | java | public void readLed(Callback<LedColor> callback) {
addCallback(BeanMessageID.CC_LED_READ_ALL, callback);
sendMessageWithoutPayload(BeanMessageID.CC_LED_READ_ALL);
} | [
"public",
"void",
"readLed",
"(",
"Callback",
"<",
"LedColor",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"CC_LED_READ_ALL",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"CC_LED_READ_ALL",
")",
";",
... | Read the LED color.
@param callback the callback for the {@link com.punchthrough.bean.sdk.message.LedColor}
result | [
"Read",
"the",
"LED",
"color",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L837-L840 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setAdvertising | public void setAdvertising(boolean enable) {
Buffer buffer = new Buffer();
buffer.writeByte(enable ? 1 : 0);
sendMessage(BeanMessageID.BT_ADV_ONOFF, buffer);
} | java | public void setAdvertising(boolean enable) {
Buffer buffer = new Buffer();
buffer.writeByte(enable ? 1 : 0);
sendMessage(BeanMessageID.BT_ADV_ONOFF, buffer);
} | [
"public",
"void",
"setAdvertising",
"(",
"boolean",
"enable",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeByte",
"(",
"enable",
"?",
"1",
":",
"0",
")",
";",
"sendMessage",
"(",
"BeanMessageID",
".",
"BT_ADV_ON... | Set the advertising flag.
@param enable true to enable, false to disable | [
"Set",
"the",
"advertising",
"flag",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L847-L851 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readTemperature | public void readTemperature(Callback<Integer> callback) {
addCallback(BeanMessageID.CC_TEMP_READ, callback);
sendMessageWithoutPayload(BeanMessageID.CC_TEMP_READ);
} | java | public void readTemperature(Callback<Integer> callback) {
addCallback(BeanMessageID.CC_TEMP_READ, callback);
sendMessageWithoutPayload(BeanMessageID.CC_TEMP_READ);
} | [
"public",
"void",
"readTemperature",
"(",
"Callback",
"<",
"Integer",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"CC_TEMP_READ",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"CC_TEMP_READ",
")",
";",
... | Request a temperature reading.
@param callback the callback for the temperature result, in degrees Celsius | [
"Request",
"a",
"temperature",
"reading",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L858-L861 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readAcceleration | public void readAcceleration(Callback<Acceleration> callback) {
addCallback(BeanMessageID.CC_ACCEL_READ, callback);
sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_READ);
} | java | public void readAcceleration(Callback<Acceleration> callback) {
addCallback(BeanMessageID.CC_ACCEL_READ, callback);
sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_READ);
} | [
"public",
"void",
"readAcceleration",
"(",
"Callback",
"<",
"Acceleration",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"CC_ACCEL_READ",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"CC_ACCEL_READ",
")",... | Request an acceleration sensor reading.
@param callback the callback for the {@link com.punchthrough.bean.sdk.message.Acceleration}
result | [
"Request",
"an",
"acceleration",
"sensor",
"reading",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L869-L872 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readSketchMetadata | public void readSketchMetadata(Callback<SketchMetadata> callback) {
addCallback(BeanMessageID.BL_GET_META, callback);
sendMessageWithoutPayload(BeanMessageID.BL_GET_META);
} | java | public void readSketchMetadata(Callback<SketchMetadata> callback) {
addCallback(BeanMessageID.BL_GET_META, callback);
sendMessageWithoutPayload(BeanMessageID.BL_GET_META);
} | [
"public",
"void",
"readSketchMetadata",
"(",
"Callback",
"<",
"SketchMetadata",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"BL_GET_META",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"BL_GET_META",
")",... | Request the sketch metadata.
@param callback the callback for the {@link com.punchthrough.bean.sdk.message.SketchMetadata}
result | [
"Request",
"the",
"sketch",
"metadata",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L880-L883 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readScratchData | public void readScratchData(ScratchBank bank, Callback<ScratchData> callback) {
addCallback(BeanMessageID.BT_GET_SCRATCH, callback);
Buffer buffer = new Buffer();
buffer.writeByte(intToByte(bank.getRawValue()));
sendMessage(BeanMessageID.BT_GET_SCRATCH, buffer);
} | java | public void readScratchData(ScratchBank bank, Callback<ScratchData> callback) {
addCallback(BeanMessageID.BT_GET_SCRATCH, callback);
Buffer buffer = new Buffer();
buffer.writeByte(intToByte(bank.getRawValue()));
sendMessage(BeanMessageID.BT_GET_SCRATCH, buffer);
} | [
"public",
"void",
"readScratchData",
"(",
"ScratchBank",
"bank",
",",
"Callback",
"<",
"ScratchData",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"BT_GET_SCRATCH",
",",
"callback",
")",
";",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(... | Request a scratch bank data value.
@param bank the {@link com.punchthrough.bean.sdk.message.ScratchBank} for which data is
being requested
@param callback the callback for the result | [
"Request",
"a",
"scratch",
"bank",
"data",
"value",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L892-L897 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setAccelerometerRange | public void setAccelerometerRange(AccelerometerRange range) {
Buffer buffer = new Buffer();
buffer.writeByte(range.getRawValue());
sendMessage(BeanMessageID.CC_ACCEL_SET_RANGE, buffer);
} | java | public void setAccelerometerRange(AccelerometerRange range) {
Buffer buffer = new Buffer();
buffer.writeByte(range.getRawValue());
sendMessage(BeanMessageID.CC_ACCEL_SET_RANGE, buffer);
} | [
"public",
"void",
"setAccelerometerRange",
"(",
"AccelerometerRange",
"range",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeByte",
"(",
"range",
".",
"getRawValue",
"(",
")",
")",
";",
"sendMessage",
"(",
"BeanMessa... | Set the accelerometer range.
@param range the {@link com.punchthrough.bean.sdk.message.AccelerometerRange} to be set | [
"Set",
"the",
"accelerometer",
"range",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L904-L908 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readAccelerometerRange | public void readAccelerometerRange(Callback<AccelerometerRange> callback) {
addCallback(BeanMessageID.CC_ACCEL_GET_RANGE, callback);
sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_GET_RANGE);
} | java | public void readAccelerometerRange(Callback<AccelerometerRange> callback) {
addCallback(BeanMessageID.CC_ACCEL_GET_RANGE, callback);
sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_GET_RANGE);
} | [
"public",
"void",
"readAccelerometerRange",
"(",
"Callback",
"<",
"AccelerometerRange",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"CC_ACCEL_GET_RANGE",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"CC_AC... | Read the accelerometer range.
@param callback the callback for the result | [
"Read",
"the",
"accelerometer",
"range",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L915-L918 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setScratchData | public void setScratchData(ScratchBank bank, byte[] data) {
ScratchData sd = ScratchData.create(bank, data);
sendMessage(BeanMessageID.BT_SET_SCRATCH, sd);
} | java | public void setScratchData(ScratchBank bank, byte[] data) {
ScratchData sd = ScratchData.create(bank, data);
sendMessage(BeanMessageID.BT_SET_SCRATCH, sd);
} | [
"public",
"void",
"setScratchData",
"(",
"ScratchBank",
"bank",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"ScratchData",
"sd",
"=",
"ScratchData",
".",
"create",
"(",
"bank",
",",
"data",
")",
";",
"sendMessage",
"(",
"BeanMessageID",
".",
"BT_SET_SCRATCH",
... | Set a scratch bank data value with raw bytes.
@param bank The {@link com.punchthrough.bean.sdk.message.ScratchBank} being set
@param data The bytes to write into the scratch bank | [
"Set",
"a",
"scratch",
"bank",
"data",
"value",
"with",
"raw",
"bytes",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L926-L929 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setRadioConfig | public void setRadioConfig(RadioConfig config, boolean save) {
sendMessage(save ? BeanMessageID.BT_SET_CONFIG : BeanMessageID.BT_SET_CONFIG_NOSAVE, config);
} | java | public void setRadioConfig(RadioConfig config, boolean save) {
sendMessage(save ? BeanMessageID.BT_SET_CONFIG : BeanMessageID.BT_SET_CONFIG_NOSAVE, config);
} | [
"public",
"void",
"setRadioConfig",
"(",
"RadioConfig",
"config",
",",
"boolean",
"save",
")",
"{",
"sendMessage",
"(",
"save",
"?",
"BeanMessageID",
".",
"BT_SET_CONFIG",
":",
"BeanMessageID",
".",
"BT_SET_CONFIG_NOSAVE",
",",
"config",
")",
";",
"}"
] | Set the radio config.
@param config the {@link com.punchthrough.bean.sdk.message.RadioConfig} to set
@param save true to save the config in non-volatile storage, false otherwise. | [
"Set",
"the",
"radio",
"config",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L965-L967 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.sendSerialMessage | public void sendSerialMessage(byte[] value) {
Buffer buffer = new Buffer();
buffer.write(value);
sendMessage(BeanMessageID.SERIAL_DATA, buffer);
} | java | public void sendSerialMessage(byte[] value) {
Buffer buffer = new Buffer();
buffer.write(value);
sendMessage(BeanMessageID.SERIAL_DATA, buffer);
} | [
"public",
"void",
"sendSerialMessage",
"(",
"byte",
"[",
"]",
"value",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"write",
"(",
"value",
")",
";",
"sendMessage",
"(",
"BeanMessageID",
".",
"SERIAL_DATA",
",",
"buffe... | Send raw bytes to the Bean as a serial message.
@param value the message payload | [
"Send",
"raw",
"bytes",
"to",
"the",
"Bean",
"as",
"a",
"serial",
"message",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L974-L978 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setPin | public void setPin(int pin, boolean active) {
Buffer buffer = new Buffer();
buffer.writeIntLe(pin);
buffer.writeByte(active ? 1 : 0);
sendMessage(BeanMessageID.BT_SET_PIN, buffer);
} | java | public void setPin(int pin, boolean active) {
Buffer buffer = new Buffer();
buffer.writeIntLe(pin);
buffer.writeByte(active ? 1 : 0);
sendMessage(BeanMessageID.BT_SET_PIN, buffer);
} | [
"public",
"void",
"setPin",
"(",
"int",
"pin",
",",
"boolean",
"active",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeIntLe",
"(",
"pin",
")",
";",
"buffer",
".",
"writeByte",
"(",
"active",
"?",
"1",
":",
... | Set the Bean's security code.
@param pin the 6 digit pin as a number, e.g. <code>123456</code>
@param active true to enable authenticated mode, false to disable the current pin | [
"Set",
"the",
"Bean",
"s",
"security",
"code",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L986-L991 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.sendSerialMessage | public void sendSerialMessage(String value) {
Buffer buffer = new Buffer();
try {
buffer.write(value.getBytes("UTF-8"));
sendMessage(BeanMessageID.SERIAL_DATA, buffer);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | java | public void sendSerialMessage(String value) {
Buffer buffer = new Buffer();
try {
buffer.write(value.getBytes("UTF-8"));
sendMessage(BeanMessageID.SERIAL_DATA, buffer);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | [
"public",
"void",
"sendSerialMessage",
"(",
"String",
"value",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"try",
"{",
"buffer",
".",
"write",
"(",
"value",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
")",
";",
"sendMessage",
"(",
"B... | Send a UTF-8 string to the Bean as a serial message.
@param value the message to send as UTF-8 bytes | [
"Send",
"a",
"UTF",
"-",
"8",
"string",
"to",
"the",
"Bean",
"as",
"a",
"serial",
"message",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L998-L1006 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readFirmwareVersion | public void readFirmwareVersion(final Callback<String> callback) {
gattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
callback.onResult(version);
}
});
} | java | public void readFirmwareVersion(final Callback<String> callback) {
gattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
callback.onResult(version);
}
});
} | [
"public",
"void",
"readFirmwareVersion",
"(",
"final",
"Callback",
"<",
"String",
">",
"callback",
")",
"{",
"gattClient",
".",
"getDeviceProfile",
"(",
")",
".",
"getFirmwareVersion",
"(",
"new",
"DeviceProfile",
".",
"VersionCallback",
"(",
")",
"{",
"@",
"O... | Read the Bean hardware version
@param callback the callback for the version string | [
"Read",
"the",
"Bean",
"hardware",
"version"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1027-L1034 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readHardwareVersion | public void readHardwareVersion(final Callback<String> callback) {
gattClient.getDeviceProfile().getHardwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
callback.onResult(version);
}
});
} | java | public void readHardwareVersion(final Callback<String> callback) {
gattClient.getDeviceProfile().getHardwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
callback.onResult(version);
}
});
} | [
"public",
"void",
"readHardwareVersion",
"(",
"final",
"Callback",
"<",
"String",
">",
"callback",
")",
"{",
"gattClient",
".",
"getDeviceProfile",
"(",
")",
".",
"getHardwareVersion",
"(",
"new",
"DeviceProfile",
".",
"VersionCallback",
"(",
")",
"{",
"@",
"O... | Read Bean firmware version
@param callback the callback for the version string | [
"Read",
"Bean",
"firmware",
"version"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1041-L1048 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setArduinoEnabled | public void setArduinoEnabled(boolean enable) {
Buffer buffer = new Buffer();
buffer.writeByte(enable ? 1 : 0);
sendMessage(BeanMessageID.CC_POWER_ARDUINO, buffer);
} | java | public void setArduinoEnabled(boolean enable) {
Buffer buffer = new Buffer();
buffer.writeByte(enable ? 1 : 0);
sendMessage(BeanMessageID.CC_POWER_ARDUINO, buffer);
} | [
"public",
"void",
"setArduinoEnabled",
"(",
"boolean",
"enable",
")",
"{",
"Buffer",
"buffer",
"=",
"new",
"Buffer",
"(",
")",
";",
"buffer",
".",
"writeByte",
"(",
"enable",
"?",
"1",
":",
"0",
")",
";",
"sendMessage",
"(",
"BeanMessageID",
".",
"CC_POW... | Enable or disable the Arduino.
@param enable true to enable, false to disable | [
"Enable",
"or",
"disable",
"the",
"Arduino",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1055-L1059 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readArduinoPowerState | public void readArduinoPowerState(final Callback<Boolean> callback) {
addCallback(BeanMessageID.CC_GET_AR_POWER, callback);
sendMessageWithoutPayload(BeanMessageID.CC_GET_AR_POWER);
} | java | public void readArduinoPowerState(final Callback<Boolean> callback) {
addCallback(BeanMessageID.CC_GET_AR_POWER, callback);
sendMessageWithoutPayload(BeanMessageID.CC_GET_AR_POWER);
} | [
"public",
"void",
"readArduinoPowerState",
"(",
"final",
"Callback",
"<",
"Boolean",
">",
"callback",
")",
"{",
"addCallback",
"(",
"BeanMessageID",
".",
"CC_GET_AR_POWER",
",",
"callback",
")",
";",
"sendMessageWithoutPayload",
"(",
"BeanMessageID",
".",
"CC_GET_AR... | Read the Arduino power state.
@param callback the callback for the power state result: true if the Arduino is on | [
"Read",
"the",
"Arduino",
"power",
"state",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1066-L1069 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.readBatteryLevel | public void readBatteryLevel(final Callback<BatteryLevel> callback) {
gattClient.getBatteryProfile().getBatteryLevel(new BatteryLevelCallback() {
@Override
public void onBatteryLevel(int percentage) {
callback.onResult(new BatteryLevel(percentage));
}
});
} | java | public void readBatteryLevel(final Callback<BatteryLevel> callback) {
gattClient.getBatteryProfile().getBatteryLevel(new BatteryLevelCallback() {
@Override
public void onBatteryLevel(int percentage) {
callback.onResult(new BatteryLevel(percentage));
}
});
} | [
"public",
"void",
"readBatteryLevel",
"(",
"final",
"Callback",
"<",
"BatteryLevel",
">",
"callback",
")",
"{",
"gattClient",
".",
"getBatteryProfile",
"(",
")",
".",
"getBatteryLevel",
"(",
"new",
"BatteryLevelCallback",
"(",
")",
"{",
"@",
"Override",
"public"... | Read the battery level.
@param callback the callback for the {@link com.punchthrough.bean.sdk.message.BatteryLevel}
result | [
"Read",
"the",
"battery",
"level",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1077-L1084 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.programWithFirmware | public OADProfile.OADApproval programWithFirmware(FirmwareBundle bundle, OADProfile.OADListener listener) {
return gattClient.getOADProfile().programWithFirmware(bundle, listener);
} | java | public OADProfile.OADApproval programWithFirmware(FirmwareBundle bundle, OADProfile.OADListener listener) {
return gattClient.getOADProfile().programWithFirmware(bundle, listener);
} | [
"public",
"OADProfile",
".",
"OADApproval",
"programWithFirmware",
"(",
"FirmwareBundle",
"bundle",
",",
"OADProfile",
".",
"OADListener",
"listener",
")",
"{",
"return",
"gattClient",
".",
"getOADProfile",
"(",
")",
".",
"programWithFirmware",
"(",
"bundle",
",",
... | Programs the Bean with new firmware images.
@param bundle The firmware package holding A and B images to be sent to the Bean
@param listener OADListener to alert the client of OAD state | [
"Programs",
"the",
"Bean",
"with",
"new",
"firmware",
"images",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1141-L1143 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/CacheItem.java | CacheItem.isTargetClassAndCurrentJvmTargetClassMatch | public boolean isTargetClassAndCurrentJvmTargetClassMatch() {
Class<?> targetClassOnThisJVM;
// JVM에 Class가 없는 상황
try {
targetClassOnThisJVM = Class.forName(targetClassName);
} catch (ClassNotFoundException e) {
log.error("target class " + targetClassName + " does not exist on this JVM.");
return false;
}
ObjectStreamClass osc = ObjectStreamClass.lookup(targetClassOnThisJVM);
// JVM Class가 Not serializable
if (osc == null) {
return false;
}
return targetClassSerialVersionUID == osc.getSerialVersionUID();
} | java | public boolean isTargetClassAndCurrentJvmTargetClassMatch() {
Class<?> targetClassOnThisJVM;
// JVM에 Class가 없는 상황
try {
targetClassOnThisJVM = Class.forName(targetClassName);
} catch (ClassNotFoundException e) {
log.error("target class " + targetClassName + " does not exist on this JVM.");
return false;
}
ObjectStreamClass osc = ObjectStreamClass.lookup(targetClassOnThisJVM);
// JVM Class가 Not serializable
if (osc == null) {
return false;
}
return targetClassSerialVersionUID == osc.getSerialVersionUID();
} | [
"public",
"boolean",
"isTargetClassAndCurrentJvmTargetClassMatch",
"(",
")",
"{",
"Class",
"<",
"?",
">",
"targetClassOnThisJVM",
";",
"// JVM에 Class가 없는 상황",
"try",
"{",
"targetClassOnThisJVM",
"=",
"Class",
".",
"forName",
"(",
"targetClassName",
")",
";",
"}",
"c... | Compare targetClassSerialVersionUID and current JVM's targetClass serialVersionUID.
If they are same return true else return false. | [
"Compare",
"targetClassSerialVersionUID",
"and",
"current",
"JVM",
"s",
"targetClass",
"serialVersionUID",
".",
"If",
"they",
"are",
"same",
"return",
"true",
"else",
"return",
"false",
"."
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/CacheItem.java#L124-L142 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/CacheItem.java | CacheItem.checkIfClassVersionApplicable | public static boolean checkIfClassVersionApplicable(Object cacheEntry, boolean useStructuredCache) {
if (!useStructuredCache && cacheEntry instanceof CacheEntry) {
return true;
}
if (useStructuredCache && cacheEntry instanceof Map) {
return true;
}
return false;
} | java | public static boolean checkIfClassVersionApplicable(Object cacheEntry, boolean useStructuredCache) {
if (!useStructuredCache && cacheEntry instanceof CacheEntry) {
return true;
}
if (useStructuredCache && cacheEntry instanceof Map) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"checkIfClassVersionApplicable",
"(",
"Object",
"cacheEntry",
",",
"boolean",
"useStructuredCache",
")",
"{",
"if",
"(",
"!",
"useStructuredCache",
"&&",
"cacheEntry",
"instanceof",
"CacheEntry",
")",
"{",
"return",
"true",
";",
"}",
... | Check if class version comparable. | [
"Check",
"if",
"class",
"version",
"comparable",
"."
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/CacheItem.java#L148-L157 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/GattClient.java | GattClient.refreshDeviceCache | private void refreshDeviceCache(BluetoothGatt gatt) {
try {
BluetoothGatt localBluetoothGatt = gatt;
Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
if (localMethod != null) {
localMethod.invoke(localBluetoothGatt, new Object[0]);
} else {
Log.e(TAG, "Couldn't find local method: refresh");
}
}
catch (Exception localException) {
Log.e(TAG, "An exception occurred while refreshing device");
}
} | java | private void refreshDeviceCache(BluetoothGatt gatt) {
try {
BluetoothGatt localBluetoothGatt = gatt;
Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
if (localMethod != null) {
localMethod.invoke(localBluetoothGatt, new Object[0]);
} else {
Log.e(TAG, "Couldn't find local method: refresh");
}
}
catch (Exception localException) {
Log.e(TAG, "An exception occurred while refreshing device");
}
} | [
"private",
"void",
"refreshDeviceCache",
"(",
"BluetoothGatt",
"gatt",
")",
"{",
"try",
"{",
"BluetoothGatt",
"localBluetoothGatt",
"=",
"gatt",
";",
"Method",
"localMethod",
"=",
"localBluetoothGatt",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"\"refresh\"... | Attempt to invalidate Androids internal GATT table cache
http://stackoverflow.com/a/22709467/5640435
@param gatt BluetoothGatt object | [
"Attempt",
"to",
"invalidate",
"Androids",
"internal",
"GATT",
"table",
"cache"
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/GattClient.java#L92-L105 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-spymemcached-adapter/src/main/java/kr/pe/kwonnam/hibernate4memcached/spymemcached/SpyMemcachedAdapter.java | SpyMemcachedAdapter.createConnectionFactoryBuilder | protected ConnectionFactoryBuilder createConnectionFactoryBuilder(OverridableReadOnlyProperties properties) {
ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
// BINARY Only!!! spymemcached incr/decr correctly supports only BINARY mode.
builder.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY);
builder.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
builder.setUseNagleAlgorithm(false);
builder.setFailureMode(FailureMode.Redistribute);
String hashAlgorithmProeprty = properties.getRequiredProperty(HASH_ALGORITHM_PROPERTY_KEY);
builder.setHashAlg(DefaultHashAlgorithm.valueOf(hashAlgorithmProeprty));
String operationTimeoutProperty = properties.getRequiredProperty(OPERATION_TIMEOUT_MILLIS_PROPERTY_KEY);
builder.setOpTimeout(Long.parseLong(operationTimeoutProperty));
String transcoderClassProperty = properties.getRequiredProperty(TRANSCODER_PROPERTY_KEY);
builder.setTranscoder(createTranscoder(properties, transcoderClassProperty));
authenticate(builder, properties);
return builder;
} | java | protected ConnectionFactoryBuilder createConnectionFactoryBuilder(OverridableReadOnlyProperties properties) {
ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
// BINARY Only!!! spymemcached incr/decr correctly supports only BINARY mode.
builder.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY);
builder.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
builder.setUseNagleAlgorithm(false);
builder.setFailureMode(FailureMode.Redistribute);
String hashAlgorithmProeprty = properties.getRequiredProperty(HASH_ALGORITHM_PROPERTY_KEY);
builder.setHashAlg(DefaultHashAlgorithm.valueOf(hashAlgorithmProeprty));
String operationTimeoutProperty = properties.getRequiredProperty(OPERATION_TIMEOUT_MILLIS_PROPERTY_KEY);
builder.setOpTimeout(Long.parseLong(operationTimeoutProperty));
String transcoderClassProperty = properties.getRequiredProperty(TRANSCODER_PROPERTY_KEY);
builder.setTranscoder(createTranscoder(properties, transcoderClassProperty));
authenticate(builder, properties);
return builder;
} | [
"protected",
"ConnectionFactoryBuilder",
"createConnectionFactoryBuilder",
"(",
"OverridableReadOnlyProperties",
"properties",
")",
"{",
"ConnectionFactoryBuilder",
"builder",
"=",
"new",
"ConnectionFactoryBuilder",
"(",
")",
";",
"// BINARY Only!!! spymemcached incr/decr correctly s... | creating ConnectionFactoryBuilder object. Override thid method if you need. | [
"creating",
"ConnectionFactoryBuilder",
"object",
".",
"Override",
"thid",
"method",
"if",
"you",
"need",
"."
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-spymemcached-adapter/src/main/java/kr/pe/kwonnam/hibernate4memcached/spymemcached/SpyMemcachedAdapter.java#L71-L91 | train |
kwon37xi/hibernate4-memcached | hibernate4-memcached-spymemcached-adapter/src/main/java/kr/pe/kwonnam/hibernate4memcached/spymemcached/SpyMemcachedAdapter.java | SpyMemcachedAdapter.getNamespacedKey | String getNamespacedKey(CacheNamespace cacheNamespace, String key) {
String namespaceIndicator = getNamespaceIndicator(cacheNamespace);
if (cacheNamespace.isNamespaceExpirationRequired() == false) {
return namespaceIndicator + ":" + key;
}
String namespaceIndicatorKey = namespaceIndicator + NAMESPACE_NAME_SQUENCE_SEPARATOR;
long namespaceSquence = memcachedClient.incr(namespaceIndicatorKey, 0L, System.currentTimeMillis(),
DEFAULT_NAMESPACE_SEQUENCE_EXPIRY_SECONDS);
return namespaceIndicatorKey + namespaceSquence + ":" + key;
} | java | String getNamespacedKey(CacheNamespace cacheNamespace, String key) {
String namespaceIndicator = getNamespaceIndicator(cacheNamespace);
if (cacheNamespace.isNamespaceExpirationRequired() == false) {
return namespaceIndicator + ":" + key;
}
String namespaceIndicatorKey = namespaceIndicator + NAMESPACE_NAME_SQUENCE_SEPARATOR;
long namespaceSquence = memcachedClient.incr(namespaceIndicatorKey, 0L, System.currentTimeMillis(),
DEFAULT_NAMESPACE_SEQUENCE_EXPIRY_SECONDS);
return namespaceIndicatorKey + namespaceSquence + ":" + key;
} | [
"String",
"getNamespacedKey",
"(",
"CacheNamespace",
"cacheNamespace",
",",
"String",
"key",
")",
"{",
"String",
"namespaceIndicator",
"=",
"getNamespaceIndicator",
"(",
"cacheNamespace",
")",
";",
"if",
"(",
"cacheNamespace",
".",
"isNamespaceExpirationRequired",
"(",
... | Return cache namespace decorated key.
@param cacheNamespace cache namespace
@param key cache key
@return namespace infomation prefixed cache key | [
"Return",
"cache",
"namespace",
"decorated",
"key",
"."
] | e0b2839ab257b2602344f54ca53c564044f3585d | https://github.com/kwon37xi/hibernate4-memcached/blob/e0b2839ab257b2602344f54ca53c564044f3585d/hibernate4-memcached-spymemcached-adapter/src/main/java/kr/pe/kwonnam/hibernate4memcached/spymemcached/SpyMemcachedAdapter.java#L133-L145 | train |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java | FirmwareImage.uint16FromData | private int uint16FromData(int offset) {
return twoBytesToInt(
Arrays.copyOfRange(data(), offset, offset + 2),
Constants.CC2540_BYTE_ORDER
);
} | java | private int uint16FromData(int offset) {
return twoBytesToInt(
Arrays.copyOfRange(data(), offset, offset + 2),
Constants.CC2540_BYTE_ORDER
);
} | [
"private",
"int",
"uint16FromData",
"(",
"int",
"offset",
")",
"{",
"return",
"twoBytesToInt",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"data",
"(",
")",
",",
"offset",
",",
"offset",
"+",
"2",
")",
",",
"Constants",
".",
"CC2540_BYTE_ORDER",
")",
";",
"}... | Parse a little-endian UInt16 from the data at the given offset.
@param offset The offset at which to parse data
@return The Java int representation of the parsed bytes | [
"Parse",
"a",
"little",
"-",
"endian",
"UInt16",
"from",
"the",
"data",
"at",
"the",
"given",
"offset",
"."
] | dc33e8cc9258d6e028e0788d74735c75b54d1133 | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java#L39-L44 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.