_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q168300 | BinaryOutputStream.write_u32 | validation | public void write_u32(int w) throws IOException {
write_u8((w >> 24) & 0xFF);
write_u8((w >> 16) & 0xFF);
write_u8((w >> 8) & 0xFF);
write_u8(w & 0xFF);
} | java | {
"resource": ""
} |
q168301 | BinaryOutputStream.write_un | validation | public void write_un(int bits, int n) throws IOException {
int mask = 1;
for(int i=0;i<n;++i) {
boolean bit = (bits & mask) != 0;
write_bit(bit);
mask = mask << 1;
}
} | java | {
"resource": ""
} |
q168302 | Build.printSyntacticMarkers | validation | public static void printSyntacticMarkers(PrintStream output, Collection<Path.Entry<?>> sources, Path.Entry<?> target) throws IOException {
// Extract all syntactic markers from entries in the build graph
List<SyntacticItem.Marker> items = extractSyntacticMarkers(target);
// For each marker, print out error messages appropriately
for (int i = 0; i != items.size(); ++i) {
// Log the error message
printSyntacticMarkers(output, sources, items.get(i));
}
} | java | {
"resource": ""
} |
q168303 | Build.printSyntacticMarkers | validation | private static void printSyntacticMarkers(PrintStream output, Collection<Path.Entry<?>> sources, SyntacticItem.Marker marker) {
//
Path.Entry<?> source = getSourceEntry(sources,marker.getSource());
//
Span span = marker.getTarget().getAncestor(AbstractCompilationUnit.Attribute.Span.class);
// Read the enclosing line so we can print it
EnclosingLine line = readEnclosingLine(source, span);
// Sanity check we found it
if(line != null) {
// print the error message
output.println(source.location() + ":" + line.lineNumber + ": " + marker.getMessage());
// Finally print the line highlight
printLineHighlight(output, line);
} else {
output.println(source.location() + ":?: " + marker.getMessage());
}
} | java | {
"resource": ""
} |
q168304 | Build.extractSyntacticMarkers | validation | private static List<SyntacticItem.Marker> extractSyntacticMarkers(Path.Entry<?>... binaries) throws IOException {
List<SyntacticItem.Marker> annotated = new ArrayList<>();
//
for (Path.Entry<?> binary : binaries) {
Object o = binary.read();
// If the object in question can be decoded as a syntactic heap then we can look
// for syntactic messages.
if (o instanceof SyntacticHeap) {
SyntacticHeap h = (SyntacticHeap) o;
extractSyntacticMarkers(h.getRootItem(), annotated, new BitSet());
}
}
//
return annotated;
} | java | {
"resource": ""
} |
q168305 | AbstractSyntacticItem.getParent | validation | @Override
public <T extends SyntacticItem> T getParent(Class<T> kind) {
return parent.getParent(this, kind);
} | java | {
"resource": ""
} |
q168306 | AbstractSyntacticItem.getParents | validation | @Override
public <T extends SyntacticItem> List<T> getParents(Class<T> kind) {
return parent.getParents(this, kind);
} | java | {
"resource": ""
} |
q168307 | AbstractSyntacticItem.getAncestor | validation | @Override
public <T extends SyntacticItem> T getAncestor(Class<T> kind) {
return parent.getAncestor(this, kind);
} | java | {
"resource": ""
} |
q168308 | ArrayUtils.append | validation | public static int[] append(int lhs, int[] rhs) {
int[] rs = new int[rhs.length+1];
rs[0] = lhs;
System.arraycopy(rhs, 0, rs, 1, rhs.length);
return rs;
} | java | {
"resource": ""
} |
q168309 | ArrayUtils.append | validation | public static int[] append(int first, int second, int[] rhs) {
int[] rs = new int[rhs.length+2];
rs[0] = first;
rs[1] = second;
System.arraycopy(rhs, 0, rs, 2, rhs.length);
return rs;
} | java | {
"resource": ""
} |
q168310 | ArrayUtils.append | validation | public static int[] append(int[] lhs, int[] rhs) {
int[] rs = java.util.Arrays.copyOf(lhs, lhs.length + rhs.length);
System.arraycopy(rhs, 0, rs, lhs.length, rhs.length);
return rs;
} | java | {
"resource": ""
} |
q168311 | ArrayUtils.append | validation | public static <T> T[] append(Class<T> type, T lhs, T... rhs) {
T[] rs = (T[]) Array.newInstance(type, rhs.length+1);
System.arraycopy(rhs, 0, rs, 1, rhs.length);
rs[0] = lhs;
return rs;
} | java | {
"resource": ""
} |
q168312 | ArrayUtils.addAll | validation | public static <T> void addAll(T[] lhs, Collection<T> rhs) {
for(int i=0;i!=lhs.length;++i) {
rhs.add(lhs[i]);
}
} | java | {
"resource": ""
} |
q168313 | ArrayUtils.toStringArray | validation | public static String[] toStringArray(Collection<String> items) {
String[] result = new String[items.size()];
int i = 0;
for(String s : items) {
result[i++] = s;
}
return result;
} | java | {
"resource": ""
} |
q168314 | ArrayUtils.toIntArray | validation | public static int[] toIntArray(Collection<Integer> items) {
int[] result = new int[items.size()];
int i = 0;
for (Integer v : items) {
result[i++] = v;
}
return result;
} | java | {
"resource": ""
} |
q168315 | ArrayUtils.sortAndRemoveDuplicates | validation | public static <T extends S, S extends Comparable<S>> T[] sortAndRemoveDuplicates(T[] children) {
int r = isSortedAndUnique(children);
switch (r) {
case 0:
// In this case, the array is already sorted and no duplicates were
// found.
return children;
case 1:
// In this case, the array is already sorted, but duplicates were
// found
return ArrayUtils.sortedRemoveDuplicates(children);
default:
// In this case, the array is not sorted and may or may not
// contain duplicates.
children = Arrays.copyOf(children, children.length);
Arrays.sort(children);
return ArrayUtils.sortedRemoveDuplicates(children);
}
} | java | {
"resource": ""
} |
q168316 | ArrayUtils.isSortedAndUnique | validation | public static <T extends Comparable<T>> int isSortedAndUnique(T[] children) {
int r = 0;
for (int i = 1; i < children.length; ++i) {
int c = children[i - 1].compareTo(children[i]);
if (c == 0) {
// Duplicate found, though still could be in sorted order.
r = 1;
} else if (c > 0) {
// NOT in sorted order
return -1;
}
}
// All good
return r;
} | java | {
"resource": ""
} |
q168317 | ArrayUtils.compareTo | validation | public static <S,T extends Comparable<S>> int compareTo(T[] lhs, T[] rhs) {
if(lhs.length != rhs.length) {
return lhs.length - rhs.length;
} else {
for(int i=0;i!=lhs.length;++i) {
int r = lhs[i].compareTo((S) rhs[i]);
if(r != 0) {
return r;
}
}
return 0;
}
} | java | {
"resource": ""
} |
q168318 | WyMain.getBuildSchema | validation | public Configuration.Schema getBuildSchema() {
Configuration.Schema[] schemas = new Configuration.Schema[buildPlatforms.size() + 1];
schemas[0] = LOCAL_CONFIG_SCHEMA;
for (int i = 0; i != buildPlatforms.size(); ++i) {
wybs.lang.Build.Platform platform = buildPlatforms.get(i);
schemas[i + 1] = platform.getConfigurationSchema();
}
return Configuration.toCombinedSchema(schemas);
} | java | {
"resource": ""
} |
q168319 | WyMain.createTemplateExtensionPoint | validation | private void createTemplateExtensionPoint() {
context.create(Command.Descriptor.class, new Module.ExtensionPoint<Command.Descriptor>() {
@Override
public void register(Command.Descriptor command) {
commandDescriptors.add(command);
}
});
} | java | {
"resource": ""
} |
q168320 | WyMain.activateDefaultPlugins | validation | private void activateDefaultPlugins(Configuration global) {
// Determine the set of install plugins
List<Path.ID> plugins = global.matchAll(Trie.fromString("plugins/*"));
// start modules
for (Path.ID id : plugins) {
UTF8 activator = global.get(UTF8.class, id);
try {
Class<?> c = Class.forName(activator.toString());
Module.Activator instance = (Module.Activator) c.newInstance();
instance.start(context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} | java | {
"resource": ""
} |
q168321 | WyMain.determineSystemRoot | validation | private static String determineSystemRoot() throws IOException {
String whileyhome = System.getenv("WHILEYHOME");
if (whileyhome == null) {
System.err.println("error: WHILEYHOME environment variable not set");
System.exit(-1);
}
return whileyhome;
} | java | {
"resource": ""
} |
q168322 | WyMain.determineLocalRoot | validation | private static String determineLocalRoot() throws IOException {
// Determine current working directory
File dir = new File(".");
// Traverse up the directory hierarchy
while (dir != null && dir.exists() && dir.isDirectory()) {
File wyf = new File(dir + File.separator + "wy.toml");
if (wyf.exists()) {
return dir.getPath();
}
// Traverse back up the directory hierarchy looking for a suitable directory.
dir = dir.getParentFile();
}
// If we get here then it means we didn't find a root, therefore just use
// current directory.
return ".";
} | java | {
"resource": ""
} |
q168323 | WyMain.readConfigFile | validation | private static Configuration readConfigFile(String name, String dir, Configuration.Schema... schemas) throws IOException {
DirectoryRoot root = new DirectoryRoot(dir, BOOT_REGISTRY);
Path.Entry<ConfigFile> config = root.get(Trie.fromString(name), ConfigFile.ContentType);
if (config == null) {
return Configuration.EMPTY;
}
try {
// Read the configuration file
ConfigFile cf = config.read();
// Construct configuration according to given schema
return cf.toConfiguration(Configuration.toCombinedSchema(schemas));
} catch (SyntacticException e) {
e.outputSourceError(System.out, false);
System.exit(-1);
return null;
}
} | java | {
"resource": ""
} |
q168324 | StdModuleManager.getInstance | validation | public <T extends Module> T getInstance(Class<T> module) {
return (T) instances.get(module);
} | java | {
"resource": ""
} |
q168325 | StdModuleManager.start | validation | public void start() {
// Construct the URLClassLoader which will be used to load
// classes within the modules.
URL[] urls = new URL[modules.size()];
for(int i=0;i!=modules.size();++i) {
urls[i] = modules.get(i).getLocation();
}
URLClassLoader loader = new URLClassLoader(urls);
// Third, active the modules. This will give them the opportunity to
// register whatever extensions they like.
activateModules(loader);
} | java | {
"resource": ""
} |
q168326 | StdModuleManager.activateModules | validation | private void activateModules(URLClassLoader loader) {
for (int i = 0; i != modules.size(); ++i) {
Descriptor module = modules.get(i);
try {
Class c = loader.loadClass(module.getActivator());
Module.Activator self = (Module.Activator) c.newInstance();
Module instance = self.start(context);
instances.put(c, instance);
logger.logTimedMessage("Activated module " + module.getId() + " (v" + module.getVersion() + ")", 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
} | java | {
"resource": ""
} |
q168327 | SyntacticException.outputSourceError | validation | public void outputSourceError(PrintStream output, boolean brief) {
Attribute.Span span;
if (entry == null || element == null) {
output.println("syntax error: " + getMessage());
return;
} else if(element instanceof Attribute.Span) {
span = (Attribute.Span) element;
} else {
SyntacticHeap parent = element.getHeap();
span = parent.getParent(element,Attribute.Span.class);
}
//
EnclosingLine enclosing = (span == null) ? null : readEnclosingLine(entry, span);
if(enclosing == null) {
output.println("syntax error: " + getMessage());
} else if(brief) {
printBriefError(output,entry,enclosing,getMessage());
} else {
printFullError(output,entry,enclosing,getMessage());
}
} | java | {
"resource": ""
} |
q168328 | SequentialBuildExecutor.ready | validation | private boolean ready(Build.Task task) {
// FIXME: this is not a great solution in the long run for several reasons.
// Firstly, its possible that a given source will be rebuilt in the near future
// as a result of some other task and we should be waiting for that.
Path.Entry<?> target = task.getTarget();
for(Path.Entry<?> s : task.getSources()) {
if(s.lastModified() > target.lastModified()) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q168329 | OptArg.parseOptions | validation | public static Map<String,Object> parseOptions(List<String> args, OptArg... options) {
HashMap<String,Object> result = new HashMap<>();
HashMap<String,OptArg> optmap = new HashMap<>();
for(OptArg opt : options) {
if(opt.defaultValue != null) {
result.put(opt.option, opt.defaultValue);
}
optmap.put(opt.option, opt);
optmap.put(opt.shortForm, opt);
}
Iterator<String> iter = args.iterator();
while(iter.hasNext()) {
String arg = iter.next();
if (arg.startsWith("-")) {
arg = arg.substring(1,arg.length());
OptArg opt = optmap.get(arg);
if(opt != null) {
// matched
iter.remove(); // remove option from args list
Kind k = opt.argument;
if(k != null) {
String param = iter.next();
iter.remove();
k.process(opt.option,param,result);
} else {
result.put(opt.option,null);
}
} else {
throw new RuntimeException("unknown command-line option: -" + arg);
}
}
}
return result;
} | java | {
"resource": ""
} |
q168330 | OptArg.splitConfig | validation | private static Map<String, Object> splitConfig(String str) {
HashMap<String, Object> options = new HashMap<>();
String[] splits = str.split(",");
for (String s : splits) {
String[] p = s.split("=");
options.put(p[0], parseValue(p[1]));
}
return options;
} | java | {
"resource": ""
} |
q168331 | AbstractSyntacticHeap.getParent | validation | @Override
public <T extends SyntacticItem> T getParent(SyntacticItem child, Class<T> kind) {
// FIXME: this could be optimised a *lot*
for (int i = 0; i != syntacticItems.size(); ++i) {
SyntacticItem parent = syntacticItems.get(i);
if(kind.isInstance(parent)) {
for(int j=0;j!=parent.size();++j) {
if(parent.get(j) == child) {
return (T) parent;
}
}
}
}
// no match
return null;
} | java | {
"resource": ""
} |
q168332 | AbstractSyntacticHeap.getAncestor | validation | @Override
public <T extends SyntacticItem> T getAncestor(SyntacticItem child, Class<T> kind) {
// FIXME: this could be optimised a *lot*
if (kind.isInstance(child)) {
return (T) child;
} else {
for (int i = 0; i != syntacticItems.size(); ++i) {
SyntacticItem parent = syntacticItems.get(i);
for (int j = 0; j != parent.size(); ++j) {
// Don't follow cross-references
if (parent.get(j) == child && !(parent instanceof AbstractCompilationUnit.Ref)) {
// FIXME: this is not specifically efficient. It would
// be helpful if SyntacticItems actually contained
// references to their parent items.
T tmp = getAncestor(parent, kind);
if (tmp != null) {
return tmp;
}
}
}
}
// no match
return null;
}
} | java | {
"resource": ""
} |
q168333 | AbstractSyntacticHeap.substitute | validation | private static SyntacticItem substitute(SyntacticItem item, SyntacticItem from, SyntacticItem to,
Map<SyntacticItem, SyntacticItem> mapping) {
SyntacticItem sItem = mapping.get(item);
if (sItem != null) {
// We've previously substituted this item already to produce a
// potentially updated item. Therefore, simply return that item to
// ensure the original aliasing structure of the ancestor(s) is
// properly preserved.
return sItem;
} else if (item == from) {
// We've matched the item being replaced, therefore return the item
// to which it is being replaced.
return to;
} else {
SyntacticItem nItem = item;
// We need to recursively descend into children of this item looking
// for the item to replace. The challenge here is that we need to
// ensure the original item is preserved as is if there is no
// change.
SyntacticItem[] children = item.getAll();
// Initially, this will alias children. In the event of a child
// which is actually updated, then this will refer to a new array.
// That will be the signal that we need to create a new item to
// return.
SyntacticItem[] nChildren = children;
if (children != null) {
for (int i = 0; i != children.length; ++i) {
SyntacticItem child = children[i];
// Check for null, since we don't want to try and substitute
// into null.
if (child != null) {
// Perform the substitution in the given child
SyntacticItem nChild = substitute(child, from, to, mapping);
// Check whether anything was actually changed by the
// substitution.
if (nChild != child && children == nChildren) {
// Yes, the child changed and we haven't already
// cloned the children array. Hence, we'd better
// clone it now to make sure that the original item
// is preserved.
nChildren = Arrays.copyOf(children, children.length);
}
nChildren[i] = nChild;
}
}
// Now, clone the original item if necessary. This is only
// necessary if the children array as been updated in some way.
if (children != nChildren) {
// Create the new item which, at this point, will be
// detached.
nItem = item.clone(nChildren);
}
}
mapping.put(item, nItem);
return nItem;
}
} | java | {
"resource": ""
} |
q168334 | Inspect.getContentType | validation | private Content.Type<?> getContentType(String file) {
List<Content.Type<?>> cts = project.getParent().getContentTypes();
for (int i = 0; i != cts.size(); ++i) {
Content.Type<?> ct = cts.get(i);
String suffix = "." + ct.getSuffix();
if (file.endsWith(suffix)) {
return ct;
}
}
// Default is just a binary file
return Content.BinaryFile;
} | java | {
"resource": ""
} |
q168335 | Inspect.getEntry | validation | public Path.Entry<?> getEntry(String file, Content.Type<?> ct) throws IOException {
// Strip suffix
file = file.replace("." + ct.getSuffix(), "");
// Determine path id
Path.ID id = Trie.fromString(file);
// Get the file from the repository root
return project.getParent().getLocalRoot().get(id, ct);
} | java | {
"resource": ""
} |
q168336 | Inspect.inspect | validation | private void inspect(Path.Entry<?> entry, Content.Type<?> ct, boolean garbage) throws IOException {
Object o = entry.read();
if (o instanceof SyntacticHeap) {
new SyntacticHeapPrinter(new PrintWriter(out), garbage).print((SyntacticHeap) o);
} else {
inspectBinaryFile(readAllBytes(entry.inputStream()));
}
} | java | {
"resource": ""
} |
q168337 | Inspect.inspectBinaryFile | validation | private void inspectBinaryFile(byte[] bytes) {
for (int i = 0; i < bytes.length; i += width) {
out.print(String.format("0x%04X ", i));
// Print out databytes
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
out.print(String.format("%02X ", bytes[i+j]));
} else {
out.print(" ");
}
}
//
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
char c = (char) bytes[i+j];
if(c >= 32 && c < 128) {
out.print(c);
} else {
out.print(".");
}
}
}
//
out.println();
}
} | java | {
"resource": ""
} |
q168338 | SyntacticHeapReader.readItems | validation | protected Pair<Integer, SyntacticItem[]> readItems() throws IOException {
// first, write magic number
checkHeader();
// second, determine number of items
int size = in.read_uv();
// third, determine the root item
int root = in.read_uv();
//
Bytecode[] items = new Bytecode[size];
// third, read abstract syntactic items
for (int i = 0; i != items.length; ++i) {
items[i] = readItem();
}
//
return new Pair<>(root, constructItems(items));
} | java | {
"resource": ""
} |
q168339 | Trie.fromString | validation | public static Trie fromString(Path.ID id) {
if(id instanceof Trie) {
return ((Trie)id);
}
Trie r = ROOT;
for(int i=0;i!=id.size();++i) {
r = r.append(id.get(i));
}
return r;
} | java | {
"resource": ""
} |
q168340 | WyProject.DESCRIPTOR | validation | public static Command.Descriptor DESCRIPTOR(List<Command.Descriptor> descriptors) {
return new Command.Descriptor() {
@Override
public Schema getConfigurationSchema() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Option.Descriptor> getOptionDescriptors() {
return Arrays.asList(
Command.OPTION_FLAG("verbose", "generate verbose information about the build", false),
Command.OPTION_FLAG("brief", "generate brief output for syntax errors", false));
}
@Override
public Command initialise(Command environment, Configuration configuration) {
return new WyProject((WyMain) environment, configuration, System.out, System.err);
}
@Override
public String getName() {
return "wy";
}
@Override
public String getDescription() {
return "Command-line interface for the Whiley Compiler Collection";
}
@Override
public List<Command.Descriptor> getCommands() {
return descriptors;
}
};
} | java | {
"resource": ""
} |
q168341 | WyProject.getRepositoryRoot | validation | public Path.Root getRepositoryRoot() throws IOException {
Path.Root root = environment.getGlobalRoot().createRelativeRoot(REPOSITORY_PATH);
// TODO: create repository if it doesn't exist.
return root;
} | java | {
"resource": ""
} |
q168342 | WyProject.resolvePackageDependencies | validation | private void resolvePackageDependencies() throws IOException {
// FIXME: should produce a wy.lock file?
Configuration.Schema buildSchema = environment.getBuildSchema();
// Global root is where all dependencies will be stored
Path.Root repository = getRepositoryRoot();
// Dig out all the defined dependencies
List<Path.ID> deps = configuration.matchAll(Trie.fromString("dependencies/**"));
// Resolve each dependencies and add to project roots
for (int i = 0; i != deps.size(); ++i) {
Path.ID dep = deps.get(i);
// Get dependency name
String name = dep.get(1);
// Get version string
UTF8 version = configuration.get(UTF8.class, dep);
// Construct path to the config file
Trie root = Trie.fromString(name + "-v" + version);
// Attempt to resolve it.
if (!repository.exists(root, ZipFile.ContentType)) {
// TODO: employ a package resolver here
// FIXME: handle better error handling.
throw new RuntimeException("missing dependency \"" + name + "-" + version + "\"");
} else {
// Extract entry for ZipFile
Path.Entry<ZipFile> zipfile = repository.get(root, ZipFile.ContentType);
// Construct root repesenting this ZipFile
Path.Root pkgRoot = new ZipFileRoot(zipfile, environment.getContentRegistry());
// Extract configuration from package
Path.Entry<ConfigFile> entry = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType);
if(entry == null) {
throw new RuntimeException("corrupt package (missing wy.toml) \"" + name + "-" + version + "\"");
} else {
ConfigFile pkgcfg = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType).read();
// Construct a package representation of this root.
Build.Package pkg = new Package(pkgRoot,pkgcfg.toConfiguration(buildSchema));
// Add a relative ZipFile root
project.getPackages().add(pkg);
}
}
}
} | java | {
"resource": ""
} |
q168343 | ConfigFileLexer.scan | validation | public List<Token> scan() {
ArrayList<Token> tokens = new ArrayList<>();
pos = 0;
while (pos < input.length()) {
char c = input.charAt(pos);
if (Character.isDigit(c)) {
tokens.add(scanNumericConstant());
} else if (c == '"') {
tokens.add(scanStringConstant());
} else if (c == '\'') {
tokens.add(scanCharacterConstant());
} else if (isOperatorStart(c)) {
tokens.add(scanOperator());
} else if (Character.isLetter(c) || c == '_') {
tokens.add(scanIdentifier());
} else if (Character.isWhitespace(c)) {
scanWhiteSpace(tokens);
} else {
syntaxError("unknown token encountered",pos);
}
}
return tokens;
} | java | {
"resource": ""
} |
q168344 | ConfigFileLexer.syntaxError | validation | private void syntaxError(String msg, int index) {
// FIXME: this is clearly not a sensible approach
throw new SyntacticException(msg, entry, new ConfigFile.Attribute.Span(null,index,index));
} | java | {
"resource": ""
} |
q168345 | SimpleLog.logStackTrace | validation | public void logStackTrace() {
if (enabled) {
Throwable t = new Throwable();
t.fillInStackTrace();
StackTraceElement[] ste_arr = t.getStackTrace();
for (int ii = 2; ii < ste_arr.length; ii++) {
StackTraceElement ste = ste_arr[ii];
System.out.printf("%s %s%n", getIndentString(), ste);
}
}
} | java | {
"resource": ""
} |
q168346 | SimpleLog.getIndentString | validation | private String getIndentString() {
assert enabled;
if (indentString == null) {
for (int i = indentStrings.size(); i <= indentLevel; i++) {
indentStrings.add(indentStrings.get(i - 1) + INDENT_STR_ONE_LEVEL);
}
indentString = indentStrings.get(indentLevel);
}
return indentString;
} | java | {
"resource": ""
} |
q168347 | StackVer.execute | validation | boolean execute(
InstructionContext ic,
Frame inFrame,
ArrayList<InstructionContext> executionPredecessors,
InstConstraintVisitor icv,
ExecutionVisitor ev) {
stack_types.set(ic.getInstruction().getPosition(), inFrame);
return ic.execute(inFrame, executionPredecessors, icv, ev);
} | java | {
"resource": ""
} |
q168348 | StackMapUtils.add_string | validation | protected String[] add_string(String[] arr, String new_string) {
String[] new_arr = new String[arr.length + 1];
for (int ii = 0; ii < arr.length; ii++) {
new_arr[ii] = arr[ii];
}
new_arr[arr.length] = new_string;
return new_arr;
} | java | {
"resource": ""
} |
q168349 | StackMapUtils.get_attribute_name | validation | @Pure
protected final String get_attribute_name(Attribute a) {
int con_index = a.getNameIndex();
Constant c = pool.getConstant(con_index);
String att_name = ((ConstantUtf8) c).getBytes();
return att_name;
} | java | {
"resource": ""
} |
q168350 | StackMapUtils.get_stack_map_table_attribute | validation | @Pure
protected final @Nullable Attribute get_stack_map_table_attribute(MethodGen mgen) {
for (Attribute a : mgen.getCodeAttributes()) {
if (is_stack_map_table(a)) {
return a;
}
}
return null;
} | java | {
"resource": ""
} |
q168351 | StackMapUtils.get_local_variable_type_table_attribute | validation | @Pure
protected final @Nullable Attribute get_local_variable_type_table_attribute(MethodGen mgen) {
for (Attribute a : mgen.getCodeAttributes()) {
if (is_local_variable_type_table(a)) {
return a;
}
}
return null;
} | java | {
"resource": ""
} |
q168352 | StackMapUtils.find_stack_map_equal | validation | protected final StackMapEntry find_stack_map_equal(int offset) {
running_offset = -1; // no +1 on first entry
for (int i = 0; i < stack_map_table.length; i++) {
running_offset = stack_map_table[i].getByteCodeOffset() + running_offset + 1;
if (running_offset > offset) {
throw new RuntimeException("Invalid StackMap offset 1");
}
if (running_offset == offset) {
return stack_map_table[i];
}
// try next map entry
}
// no offset matched
throw new RuntimeException("Invalid StackMap offset 2");
} | java | {
"resource": ""
} |
q168353 | StackMapUtils.find_stack_map_index_before | validation | protected final int find_stack_map_index_before(int offset) {
number_active_locals = initial_locals_count;
running_offset = -1; // no +1 on first entry
for (int i = 0; i < stack_map_table.length; i++) {
running_offset = running_offset + stack_map_table[i].getByteCodeOffset() + 1;
if (running_offset >= offset) {
if (i == 0) {
// reset offset to previous
running_offset = -1;
return -1;
} else {
// back up offset to previous
running_offset = running_offset - stack_map_table[i].getByteCodeOffset() - 1;
// return previous
return i - 1;
}
}
// Update number of active locals based on this StackMap entry.
int frame_type = stack_map_table[i].getFrameType();
if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) {
number_active_locals += frame_type - 251;
} else if (frame_type >= Const.CHOP_FRAME && frame_type <= Const.CHOP_FRAME_MAX) {
number_active_locals -= 251 - frame_type;
} else if (frame_type == Const.FULL_FRAME) {
number_active_locals = stack_map_table[i].getNumberOfLocals();
}
// All other frame_types do not modify locals.
}
if (stack_map_table.length == 0) {
return -1;
} else {
return stack_map_table.length - 1;
}
} | java | {
"resource": ""
} |
q168354 | StackMapUtils.find_stack_map_index_after | validation | protected final @IndexOrLow("stack_map_table") int find_stack_map_index_after(int offset) {
running_offset = -1; // no +1 on first entry
for (int i = 0; i < stack_map_table.length; i++) {
running_offset = running_offset + stack_map_table[i].getByteCodeOffset() + 1;
if (running_offset > offset) {
return i;
}
// try next map entry
}
// no such entry found
return -1;
} | java | {
"resource": ""
} |
q168355 | StackMapUtils.build_unitialized_NEW_map | validation | protected final void build_unitialized_NEW_map(InstructionList il) {
uninitialized_NEW_map.clear();
il.setPositions();
for (StackMapEntry smte : stack_map_table) {
int frame_type = smte.getFrameType();
if ((frame_type >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME
&& frame_type <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
|| (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX)
|| (frame_type == Const.FULL_FRAME)) {
if (smte.getNumberOfLocals() > 0) {
for (StackMapType smt : smte.getTypesOfLocals()) {
if (smt.getType() == Const.ITEM_NewObject) {
int i = smt.getIndex();
uninitialized_NEW_map.put(il.findHandle(i), i);
}
}
}
if (smte.getNumberOfStackItems() > 0) {
for (StackMapType smt : smte.getTypesOfStackItems()) {
if (smt.getType() == Const.ITEM_NewObject) {
int i = smt.getIndex();
uninitialized_NEW_map.put(il.findHandle(i), i);
}
}
}
}
}
} | java | {
"resource": ""
} |
q168356 | StackMapUtils.update_NEW_object_stack_map_entries | validation | private final void update_NEW_object_stack_map_entries(int old_offset, int new_offset) {
for (StackMapEntry smte : stack_map_table) {
int frame_type = smte.getFrameType();
if ((frame_type >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME
&& frame_type <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
|| (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX)
|| (frame_type == Const.FULL_FRAME)) {
if (smte.getNumberOfLocals() > 0) {
for (StackMapType smt : smte.getTypesOfLocals()) {
if (smt.getType() == Const.ITEM_NewObject) {
if (old_offset == smt.getIndex()) {
smt.setIndex(new_offset);
}
}
}
}
if (smte.getNumberOfStackItems() > 0) {
for (StackMapType smt : smte.getTypesOfStackItems()) {
if (smt.getType() == Const.ITEM_NewObject) {
if (old_offset == smt.getIndex()) {
smt.setIndex(new_offset);
}
}
}
}
}
}
} | java | {
"resource": ""
} |
q168357 | StackMapUtils.update_uninitialized_NEW_offsets | validation | protected final void update_uninitialized_NEW_offsets(InstructionList il) {
il.setPositions();
for (Map.Entry<InstructionHandle, Integer> e : uninitialized_NEW_map.entrySet()) {
InstructionHandle ih = e.getKey();
int old_offset = e.getValue().intValue();
int new_offset = ih.getPosition();
if (old_offset != new_offset) {
update_NEW_object_stack_map_entries(old_offset, new_offset);
e.setValue(new_offset);
}
}
} | java | {
"resource": ""
} |
q168358 | StackMapUtils.set_current_stack_map_table | validation | @EnsuresNonNull({"stack_map_table"})
protected final void set_current_stack_map_table(MethodGen mgen, int java_class_version) {
smta = (StackMap) get_stack_map_table_attribute(mgen);
if (smta != null) {
// get a deep copy of the original StackMapTable.
stack_map_table = ((StackMap) (smta.copy(smta.getConstantPool()))).getStackMap();
needStackMap = true;
debug_instrument.log(
"Attribute tag: %s length: %d nameIndex: %d%n",
smta.getTag(), smta.getLength(), smta.getNameIndex());
// Delete existing stack map - we'll add a new one later.
mgen.removeCodeAttribute(smta);
} else {
stack_map_table = empty_stack_map_table;
if (java_class_version > Const.MAJOR_1_6) {
needStackMap = true;
}
}
print_stack_map_table("Original");
} | java | {
"resource": ""
} |
q168359 | StackMapUtils.print_stack_map_table | validation | protected final void print_stack_map_table(String prefix) {
debug_instrument.log("%nStackMap(%s) %s items:%n", prefix, stack_map_table.length);
running_offset = -1; // no +1 on first entry
for (int i = 0; i < stack_map_table.length; i++) {
running_offset = stack_map_table[i].getByteCodeOffset() + running_offset + 1;
debug_instrument.log("@%03d %s %n", running_offset, stack_map_table[i]);
}
} | java | {
"resource": ""
} |
q168360 | StackMapUtils.create_new_stack_map_attribute | validation | protected final void create_new_stack_map_attribute(MethodGen mgen) throws IOException {
if (!needStackMap) {
return;
}
if (stack_map_table == empty_stack_map_table) {
return;
}
print_stack_map_table("Final");
// Build new StackMapTable attribute
StackMap map_table =
new StackMap(pool.addUtf8("StackMapTable"), 0, null, pool.getConstantPool());
map_table.setStackMap(stack_map_table);
mgen.addCodeAttribute(map_table);
} | java | {
"resource": ""
} |
q168361 | StackMapUtils.typeToClassGetName | validation | @SuppressWarnings("signature") // conversion routine
protected static @ClassGetName String typeToClassGetName(Type t) {
if (t instanceof ObjectType) {
return ((ObjectType) t).getClassName();
} else if (t instanceof BasicType) {
// Use reserved keyword for basic type rather than signature to
// avoid conflicts with user defined types.
return t.toString();
} else {
// Array type: just convert '/' to '.'
return t.getSignature().replace('/', '.');
}
} | java | {
"resource": ""
} |
q168362 | StackMapUtils.generate_StackMapType_from_Type | validation | protected final StackMapType generate_StackMapType_from_Type(Type t) {
switch (t.getType()) {
case Const.T_BOOLEAN:
case Const.T_CHAR:
case Const.T_BYTE:
case Const.T_SHORT:
case Const.T_INT:
return new StackMapType(Const.ITEM_Integer, -1, pool.getConstantPool());
case Const.T_FLOAT:
return new StackMapType(Const.ITEM_Float, -1, pool.getConstantPool());
case Const.T_DOUBLE:
return new StackMapType(Const.ITEM_Double, -1, pool.getConstantPool());
case Const.T_LONG:
return new StackMapType(Const.ITEM_Long, -1, pool.getConstantPool());
case Const.T_ARRAY:
case Const.T_OBJECT:
return new StackMapType(
Const.ITEM_Object, pool.addClass(typeToClassGetName(t)), pool.getConstantPool());
// UNKNOWN seems to be used for Uninitialized objects.
// The second argument to the constructor should be the code offset
// of the corresponding 'new' instruction. Just using 0 for now.
case Const.T_UNKNOWN:
return new StackMapType(Const.ITEM_NewObject, 0, pool.getConstantPool());
default:
throw new RuntimeException("Invalid type: " + t + t.getType());
}
} | java | {
"resource": ""
} |
q168363 | StackMapUtils.generate_Type_from_StackMapType | validation | protected final Type generate_Type_from_StackMapType(StackMapType smt) {
switch (smt.getType()) {
case Const.ITEM_Integer:
case Const.ITEM_Bogus: // not sure about this; reresents 'top'?
return Type.INT;
case Const.ITEM_Float:
return Type.FLOAT;
case Const.ITEM_Double:
return Type.DOUBLE;
case Const.ITEM_Long:
return Type.LONG;
case Const.ITEM_Object:
return Type.OBJECT;
default:
Thread.dumpStack();
assert false : "Invalid StackMapType: " + smt + smt.getType();
throw new RuntimeException("Invalid StackMapType: " + smt + smt.getType());
}
} | java | {
"resource": ""
} |
q168364 | StackMapUtils.create_method_scope_local | validation | protected final LocalVariableGen create_method_scope_local(
MethodGen mgen, String local_name, Type local_type) {
// BCEL sorts local vars and presents them in offset order. Search
// locals for first var with start != 0. If none, just add the new
// var at the end of the table and exit. Otherwise, insert the new
// var just prior to the local we just found.
// Now we need to make a pass over the byte codes to update the local
// offset values of all the locals we just shifted up. This may have
// a 'knock on' effect if we are forced to change an instruction that
// references implict local #3 to an instruction with an explict
// reference to local #4 as this would require the insertion of an
// offset into the byte codes. This means we would need to make an
// additional pass to update branch targets (no - BCEL does this for
// us) and the StackMapTable (yes - BCEL should do this, but it doesn't).
//
// We never want to insert our local prior to any parameters. This would
// happen naturally, but some old class files have non zero addresses
// for 'this' and/or the parameters so we need to add an explicit
// check to make sure we skip these variables.
LocalVariableGen lv_new;
int max_offset = 0;
int new_offset = -1;
// get a copy of the local before modification
LocalVariableGen[] locals = mgen.getLocalVariables();
@IndexOrLow("locals") int compiler_temp_i = -1;
int new_index = -1;
int i;
for (i = 0; i < locals.length; i++) {
LocalVariableGen lv = locals[i];
if (i >= first_local_index) {
if (lv.getStart().getPosition() != 0) {
if (new_offset == -1) {
if (compiler_temp_i != -1) {
new_offset = locals[compiler_temp_i].getIndex();
new_index = compiler_temp_i;
} else {
new_offset = lv.getIndex();
new_index = i;
}
}
}
}
// calculate max local size seen so far (+1)
max_offset = lv.getIndex() + lv.getType().getSize();
if (lv.getName().startsWith("DaIkOnTeMp")) {
// Remember the index of a compiler temp. We may wish
// to insert our new local prior to a temp to simplfy
// the generation of StackMaps.
if (compiler_temp_i == -1) {
compiler_temp_i = i;
}
} else {
// If there were compiler temps prior to this local, we don't
// need to worry about them as the compiler will have already
// included them in the StackMaps. Reset the indicators.
compiler_temp_i = -1;
}
}
// We have looked at all the local variables; if we have not found
// a place for our new local, check to see if last local was a
// compiler temp and insert prior.
if ((new_offset == -1) && (compiler_temp_i != -1)) {
new_offset = locals[compiler_temp_i].getIndex();
new_index = compiler_temp_i;
}
// If new_offset is still unset, we can just add our local at the
// end. There may be unnamed compiler temps here, so we need to
// check for this (via max_offset) and move them up.
if (new_offset == -1) {
new_offset = max_offset;
if (new_offset < mgen.getMaxLocals()) {
mgen.setMaxLocals(mgen.getMaxLocals() + local_type.getSize());
}
lv_new = mgen.addLocalVariable(local_name, local_type, new_offset, null, null);
} else {
// insert our new local variable into existing table at 'new_offset'
lv_new = mgen.addLocalVariable(local_name, local_type, new_offset, null, null);
// we need to adjust the offset of any locals after our insertion
for (i = new_index; i < locals.length; i++) {
LocalVariableGen lv = locals[i];
lv.setIndex(lv.getIndex() + local_type.getSize());
}
mgen.setMaxLocals(mgen.getMaxLocals() + local_type.getSize());
}
debug_instrument.log(
"Added local %s%n", lv_new.getIndex() + ": " + lv_new.getName() + ", " + lv_new.getType());
// Now process the instruction list, adding one to the offset
// within each LocalVariableInstruction that references a
// local that is 'higher' in the local map than new local
// we just inserted.
adjust_code_for_locals_change(mgen, new_offset, local_type.getSize());
// Finally, we need to update any FULL_FRAME StackMap entries to
// add in the new local variable type.
update_full_frame_stack_map_entries(new_offset, local_type, locals);
debug_instrument.log("New LocalVariableTable:%n%s%n", mgen.getLocalVariableTable(pool));
return lv_new;
} | java | {
"resource": ""
} |
q168365 | StackMapUtils.bcel_calc_stack_types | validation | protected final StackTypes bcel_calc_stack_types(MethodGen mg) {
StackVer stackver = new StackVer();
VerificationResult vr;
try {
vr = stackver.do_stack_ver(mg);
} catch (Throwable t) {
System.out.printf("Warning: StackVer exception for %s.%s%n", mg.getClassName(), mg.getName());
System.out.printf("Exception: %s%n", t);
System.out.printf("Method is NOT instrumented%n");
return null;
}
if (vr != VerificationResult.VR_OK) {
System.out.printf(
"Warning: StackVer failed for %s.%s: %s%n", mg.getClassName(), mg.getName(), vr);
System.out.printf("Method is NOT instrumented%n");
return null;
}
assert vr == VerificationResult.VR_OK : " vr failed " + vr;
return stackver.get_stack_types();
} | java | {
"resource": ""
} |
q168366 | BcelUtil.accessFlagsToString | validation | static String accessFlagsToString(Method m) {
int flags = m.getAccessFlags();
StringBuilder buf = new StringBuilder();
// Note that pow is a binary mask for the flag (= 2^i).
for (int i = 0, pow = 1; i <= Const.MAX_ACC_FLAG; i++) {
if ((flags & pow) != 0) {
if (buf.length() > 0) {
buf.append(" ");
}
if (i < Const.ACCESS_NAMES_LENGTH) {
buf.append(Const.getAccessName(i));
} else {
buf.append(String.format("ACC_BIT(%x)", pow));
}
}
pow <<= 1;
}
return buf.toString();
} | java | {
"resource": ""
} |
q168367 | BcelUtil.instructionListToString | validation | public static String instructionListToString(InstructionList il, ConstantPoolGen pool) {
StringBuilder out = new StringBuilder();
for (Iterator<InstructionHandle> i = il.iterator(); i.hasNext(); ) {
InstructionHandle handle = i.next();
out.append(handle.getInstruction().toString(pool.getConstantPool()) + "\n");
}
return out.toString();
} | java | {
"resource": ""
} |
q168368 | BcelUtil.attributeNameToString | validation | public static String attributeNameToString(Attribute a) {
ConstantPool pool = a.getConstantPool();
int conIndex = a.getNameIndex();
Constant c = pool.getConstant(conIndex);
String attName = ((ConstantUtf8) c).getBytes();
return attName;
} | java | {
"resource": ""
} |
q168369 | BcelUtil.checkMgen | validation | public static void checkMgen(MethodGen mgen) {
if (skipChecks) {
return;
}
try {
mgen.toString(); // ensure it can be formatted without exceptions
mgen.getLineNumberTable(mgen.getConstantPool());
InstructionList ilist = mgen.getInstructionList();
if (ilist == null || ilist.getStart() == null) {
return;
}
CodeExceptionGen[] exceptionHandlers = mgen.getExceptionHandlers();
for (CodeExceptionGen gen : exceptionHandlers) {
assert ilist.contains(gen.getStartPC())
: "exception handler "
+ gen
+ " has been forgotten in "
+ mgen.getClassName()
+ "."
+ mgen.getName();
}
MethodGen nmg = new MethodGen(mgen.getMethod(), mgen.getClassName(), mgen.getConstantPool());
nmg.getLineNumberTable(mgen.getConstantPool());
} catch (Throwable t) {
Error e =
new Error(
String.format(
"failure while checking method %s.%s%n", mgen.getClassName(), mgen.getName()),
t);
e.printStackTrace();
throw e;
}
} | java | {
"resource": ""
} |
q168370 | BcelUtil.checkMgens | validation | public static void checkMgens(final ClassGen gen) {
if (skipChecks) {
return;
}
Method[] methods = gen.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// System.out.println ("Checking method " + method + " in class "
// + gen.getClassName());
checkMgen(new MethodGen(method, gen.getClassName(), gen.getConstantPool()));
}
// Diagnostic output
if (false) {
dumpStackTrace();
dumpMethods(gen);
}
} | java | {
"resource": ""
} |
q168371 | BcelUtil.dumpStackTrace | validation | public static void dumpStackTrace() {
StackTraceElement[] ste = Thread.currentThread().getStackTrace();
// [0] is getStackTrace
// [1] is dumpStackTrace
if (ste.length < 3) {
System.out.println("No stack trace information available");
} else {
StackTraceElement caller = ste[2];
System.out.printf(
"%s.%s (%s line %d)",
caller.getClassName(),
caller.getMethodName(),
caller.getFileName(),
caller.getLineNumber());
for (int ii = 3; ii < ste.length; ii++) {
System.out.printf(" [%s line %d]", ste[ii].getFileName(), ste[ii].getLineNumber());
}
System.out.printf("%n");
}
} | java | {
"resource": ""
} |
q168372 | BcelUtil.dumpMethods | validation | static void dumpMethods(ClassGen gen) {
System.out.printf("Class %s methods:%n", gen.getClassName());
for (Method m : gen.getMethods()) {
System.out.printf(" %s%n", m);
}
} | java | {
"resource": ""
} |
q168373 | BcelUtil.addToStart | validation | public static void addToStart(MethodGen mg, InstructionList newList) {
// Add the code before the first instruction
InstructionList il = mg.getInstructionList();
InstructionHandle oldStart = il.getStart();
InstructionHandle newStart = il.insert(newList);
// Move any LineNumbers and local variables that currently point to
// the first instruction to include the new instructions. Other
// targeters (branches, exceptions) should not include the new code.
if (oldStart.hasTargeters()) {
// getTargeters() returns non-null because hasTargeters => true
for (InstructionTargeter it : oldStart.getTargeters()) {
if ((it instanceof LineNumberGen) || (it instanceof LocalVariableGen)) {
it.updateTarget(oldStart, newStart);
}
}
}
mg.setMaxStack();
mg.setMaxLocals();
} | java | {
"resource": ""
} |
q168374 | BcelUtil.getConstantString | validation | public static String getConstantString(ConstantPool pool, int index) {
Constant c = pool.getConstant(index);
assert c != null : "Bad index " + index + " into pool";
if (c instanceof ConstantUtf8) {
return ((ConstantUtf8) c).getBytes();
} else if (c instanceof ConstantClass) {
ConstantClass cc = (ConstantClass) c;
return cc.getBytes(pool) + " [" + cc.getNameIndex() + "]";
} else {
throw new Error("unexpected constant " + c + " of class " + c.getClass());
}
} | java | {
"resource": ""
} |
q168375 | BcelUtil.resetLocalsToFormals | validation | public static void resetLocalsToFormals(MethodGen mg) {
// Get the parameter types and names.
@SuppressWarnings("nullness" // The annotation arguments might not be initialized yet.
// Since the arguments are not executed at run time, there is no null pointer exception.
)
Type @SameLen({"argTypes", "mg.getArgumentTypes()"}) [] argTypes = mg.getArgumentTypes();
@SuppressWarnings("nullness" // The annotation arguments might not be initialized yet.
// Since the arguments are not executed at run time, there is no null pointer exception.
)
String @SameLen({"argTypes", "argNames", "mg.getArgumentTypes()", "mg.getArgumentNames()"}) []
argNames = mg.getArgumentNames();
// Remove any existing locals
mg.setMaxLocals(0);
mg.removeLocalVariables();
// Add a local for the instance variable (this)
if (!mg.isStatic()) {
mg.addLocalVariable("this", new ObjectType(mg.getClassName()), null, null);
}
// Add a local for each parameter
for (int ii = 0; ii < argNames.length; ii++) {
mg.addLocalVariable(argNames[ii], argTypes[ii], null, null);
}
// Reset the current number of locals so that when other locals
// are added they get added at the correct offset.
mg.setMaxLocals();
return;
} | java | {
"resource": ""
} |
q168376 | BcelUtil.typeToClass | validation | public static Class<?> typeToClass(Type type) {
String classname = typeToClassgetname(type);
try {
return ReflectionPlume.classForName(classname);
} catch (Exception e) {
throw new RuntimeException("can't find class for " + classname, e);
}
} | java | {
"resource": ""
} |
q168377 | BcelUtil.postpendToArray | validation | public static Type[] postpendToArray(Type[] types, Type newType) {
if (types.length == Integer.MAX_VALUE) {
throw new Error("array " + types + " is too large to extend");
}
Type[] newTypes = new Type[types.length + 1];
System.arraycopy(types, 0, newTypes, 0, types.length);
newTypes[types.length] = newType;
return newTypes;
} | java | {
"resource": ""
} |
q168378 | StackTypes.set | validation | public void set(@IndexFor({"loc_arr", "os_arr"}) int offset, Frame f) {
OperandStack os = f.getStack();
// logger.info ("stack[" + offset + "] = " + toString(os));
loc_arr[offset] = (LocalVariables) (f.getLocals().clone());
os_arr[offset] = (OperandStack) (os.clone());
} | java | {
"resource": ""
} |
q168379 | InstructionListUtils.insert_at_method_start | validation | protected final void insert_at_method_start(MethodGen mg, InstructionList new_il) {
// Ignore methods with no instructions
InstructionList il = mg.getInstructionList();
if (il == null) {
return;
}
insert_before_handle(mg, il.getStart(), new_il, false);
} | java | {
"resource": ""
} |
q168380 | InstructionListUtils.print_il | validation | private void print_il(InstructionHandle start, String label) {
if (debug_instrument.enabled()) {
print_stack_map_table(label);
InstructionHandle tih = start;
while (tih != null) {
debug_instrument.log("inst: %s %n", tih);
if (tih.hasTargeters()) {
for (InstructionTargeter it : tih.getTargeters()) {
debug_instrument.log("targeter: %s %n", it);
}
}
tih = tih.getNext();
}
}
} | java | {
"resource": ""
} |
q168381 | InstructionListUtils.build_il | validation | protected final InstructionList build_il(Instruction... instructions) {
InstructionList il = new InstructionList();
for (Instruction inst : instructions) {
append_inst(il, inst);
}
return il;
} | java | {
"resource": ""
} |
q168382 | InstructionListUtils.calculate_live_stack_types | validation | protected final StackMapType[] calculate_live_stack_types(OperandStack stack) {
int ss = stack.size();
StackMapType[] stack_map_types = new StackMapType[ss];
for (int ii = 0; ii < ss; ii++) {
stack_map_types[ii] = generate_StackMapType_from_Type(stack.peek(ss - ii - 1));
}
return stack_map_types;
} | java | {
"resource": ""
} |
q168383 | StringHandler.find | validation | private static final int find(boolean skipBlocks, String s, char toFind, int from) {
int open = 0;
boolean escaping = false;
for (int i = from; i < s.length(); i++) {
if (escaping) {
escaping = false;
continue;
}
char c = s.charAt(i);
if (c == '\\') {
escaping = true;
continue;
}
if ((open == 0) && (c == toFind)) {
return i;
} else if (skipBlocks && (c == '{')) {
open++;
} else if (skipBlocks && (c == '}')) {
open--;
}
}
return -1;
} | java | {
"resource": ""
} |
q168384 | TNettyTransport.read | validation | @Override
public int read(final byte[] output, final int offset, final int length) throws TTransportException {
int read = 0;
int index = offset;
int space = length - offset;
while (space > 0) {
byte aByte = readAsynchrously();
output[index] = aByte;
space--;
index++;
read++;
}
return read;
} | java | {
"resource": ""
} |
q168385 | TNettyTransport.flush | validation | @Override
public void flush() throws TTransportException {
ChannelBuffer flush = ChannelBuffers.dynamicBuffer();
flush.writeBytes(output);
channel.write(flush).awaitUninterruptibly();
} | java | {
"resource": ""
} |
q168386 | WebSocketClientFactory.newClient | validation | public WebSocketClient newClient(final URI url, final WebSocketCallback callback) {
ClientBootstrap bootstrap = new ClientBootstrap(socketChannelFactory);
String protocol = url.getScheme();
if (!protocol.equals("ws") && !protocol.equals("wss")) {
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
}
final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, callback);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("ws-handler", clientHandler);
return pipeline;
}
});
return clientHandler;
} | java | {
"resource": ""
} |
q168387 | AdmobFetcher.canUseThisAd | validation | private boolean canUseThisAd(NativeAd adNative) {
if (adNative != null) {
NativeAd.Image logoImage = null;
CharSequence header = null, body = null;
if (adNative instanceof NativeContentAd) {
NativeContentAd ad = (NativeContentAd) adNative;
logoImage = ad.getLogo();
header = ad.getHeadline();
body = ad.getBody();
} else if (adNative instanceof NativeAppInstallAd) {
NativeAppInstallAd ad = (NativeAppInstallAd) adNative;
logoImage = ad.getIcon();
header = ad.getHeadline();
body = ad.getBody();
}
if (!TextUtils.isEmpty(header)
&& !TextUtils.isEmpty(body)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q168388 | AdmobFetcherBanner.getAdForIndex | validation | public synchronized AdView getAdForIndex(int adPos) {
if(adPos >= 0 && mPrefetchedAds.size() > adPos)
return mPrefetchedAds.get(adPos);
return null;
} | java | {
"resource": ""
} |
q168389 | AdmobFetcherBanner.onFailedToLoad | validation | private synchronized void onFailedToLoad(AdView adView, int errorCode) {
Log.i(TAG, "onAdFailedToLoad " + errorCode);
mFetchFailCount++;
mNoOfFetchedAds = Math.max(mNoOfFetchedAds - 1, 0);
//Since Fetch Ad is only called once without retries
//hide ad row / rollback its count if still not added to list
mPrefetchedAds.remove(adView);
onAdFailed(mNoOfFetchedAds - 1, errorCode, adView);
} | java | {
"resource": ""
} |
q168390 | AdmobFetcherBase.getAdRequest | validation | protected synchronized AdRequest getAdRequest() {
AdRequest.Builder adBldr = new AdRequest.Builder();
for (String id : getTestDeviceIds()) {
adBldr.addTestDevice(id);
}
return adBldr.build();
} | java | {
"resource": ""
} |
q168391 | AdmobAdapterCalculator.getAdsCountToPublish | validation | public int getAdsCountToPublish(int fetchedAdsCount, int sourceItemsCount){
if(fetchedAdsCount <= 0 || getNoOfDataBetweenAds() <= 0) return 0;
int expected = 0;
if(sourceItemsCount > 0 && sourceItemsCount >= getOffsetValue()+1)
expected = (sourceItemsCount - getOffsetValue()) / getNoOfDataBetweenAds() + 1;
expected = Math.max(0, expected);
expected = Math.min(fetchedAdsCount, expected);
return Math.min(expected, getLimitOfAds());
} | java | {
"resource": ""
} |
q168392 | AdmobAdapterCalculator.getOriginalContentPosition | validation | public int getOriginalContentPosition(int position, int fetchedAdsCount, int sourceItemsCount) {
int noOfAds = getAdsCountToPublish(fetchedAdsCount, sourceItemsCount);
// No of spaces for ads in the dataset, according to ad placement rules
int adSpacesCount = (getAdIndex(position) + 1);
int originalPosition = position - Math.min(adSpacesCount, noOfAds);
//Log.d("POSITION", position + " is originally " + originalPosition);
return originalPosition;
} | java | {
"resource": ""
} |
q168393 | AdmobAdapterCalculator.getAdIndex | validation | public int getAdIndex(int position) {
int index = -1;
if(position >= getOffsetValue())
index = (position - getOffsetValue()) / (getNoOfDataBetweenAds()+1);
//Log.d("POSITION", "index " + index + " for position " + position);
return index;
} | java | {
"resource": ""
} |
q168394 | AdmobAdapterCalculator.isAdAvailable | validation | public boolean isAdAvailable(int position, int fetchedAdsCount) {
if(fetchedAdsCount == 0) return false;
int adIndex = getAdIndex(position);
int firstAdPos = getOffsetValue();
return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds() && adIndex < fetchedAdsCount;
} | java | {
"resource": ""
} |
q168395 | AdmobAdapterCalculator.hasToFetchAd | validation | public boolean hasToFetchAd(int position, int fetchingAdsCount){
int adIndex = getAdIndex(position);
int firstAdPos = getOffsetValue();
return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds() && adIndex >= fetchingAdsCount;
} | java | {
"resource": ""
} |
q168396 | SupportedTypes.getWildcardType | validation | public static TypeMirror getWildcardType(String type, String elementType, Elements elements,
Types types) {
TypeElement arrayList = elements.getTypeElement(type);
TypeMirror elType = elements.getTypeElement(elementType).asType();
return types.getDeclaredType(arrayList, types.getWildcardType(elType, null));
} | java | {
"resource": ""
} |
q168397 | SupportedTypes.hasGenericsTypeArgumentOf | validation | public static TypeMirror hasGenericsTypeArgumentOf(Element element, String typeToCheck,
Elements elements, Types types) {
if (element.asType().getKind() != TypeKind.DECLARED
|| !(element.asType() instanceof DeclaredType)) {
ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!",
element.getSimpleName(), element.asType().toString());
}
DeclaredType declaredType = (DeclaredType) element.asType();
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (typeArguments.isEmpty()) {
ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!",
element.getSimpleName(), element.asType().toString());
}
if (typeArguments.size() > 1) {
ProcessorMessage.error(element, "The field %s in %s has more than 1 generic type argument!",
element.getSimpleName(), element.asType().toString());
}
// Ok it has a generic argument, check if this extends Parcelable
TypeMirror argument = typeArguments.get(0);
if (typeToCheck != null) {
if (!isOfType(argument, typeToCheck, elements, types)) {
ProcessorMessage.error(element,
"The fields %s generic type argument is not of type %s! (in %s )",
element.getSimpleName(), typeToCheck, element.asType().toString());
}
}
// everything is like expected
return argument;
} | java | {
"resource": ""
} |
q168398 | JavaWriter.emitPackage | validation | public JavaWriter emitPackage(String packageName) throws IOException {
if (this.packagePrefix != null) {
throw new IllegalStateException();
}
if (packageName.isEmpty()) {
this.packagePrefix = "";
} else {
out.write("package ");
out.write(packageName);
out.write(";\n\n");
this.packagePrefix = packageName + ".";
}
return this;
} | java | {
"resource": ""
} |
q168399 | JavaWriter.compressType | validation | public String compressType(String type) {
StringBuilder sb = new StringBuilder();
if (this.packagePrefix == null) {
throw new IllegalStateException();
}
Matcher m = TYPE_PATTERN.matcher(type);
int pos = 0;
while (true) {
boolean found = m.find(pos);
// Copy non-matching characters like "<".
int typeStart = found ? m.start() : type.length();
sb.append(type, pos, typeStart);
if (!found) {
break;
}
// Copy a single class name, shortening it if possible.
String name = m.group(0);
String imported = importedTypes.get(name);
if (imported != null) {
sb.append(imported);
} else if (isClassInPackage(name, packagePrefix)) {
String compressed = name.substring(packagePrefix.length());
if (isAmbiguous(compressed)) {
sb.append(name);
} else {
sb.append(compressed);
}
} else if (isClassInPackage(name, "java.lang.")) {
sb.append(name.substring("java.lang.".length()));
} else {
sb.append(name);
}
pos = m.end();
}
return sb.toString();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.