_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q100
StringGroovyMethods.getAt
train
public static CharSequence getAt(CharSequence text, int index) { index = normaliseIndex(index, text.length()); return text.subSequence(index, index + 1); }
java
{ "resource": "" }
q101
StringGroovyMethods.getAt
train
public static String getAt(GString text, int index) { return (String) getAt(text.toString(), index); }
java
{ "resource": "" }
q102
StringGroovyMethods.getAt
train
public static CharSequence getAt(CharSequence text, IntRange range) { return getAt(text, (Range) range); }
java
{ "resource": "" }
q103
StringGroovyMethods.getAt
train
public static CharSequence getAt(CharSequence text, Range range) { RangeInfo info = subListBorders(text.length(), range); CharSequence sequence = text.subSequence(info.from, info.to); return info.reverse ? reverse(sequence) : sequence; }
java
{ "resource": "" }
q104
StringGroovyMethods.getAt
train
public static String getAt(GString text, Range range) { return getAt(text.toString(), range); }
java
{ "resource": "" }
q105
StringGroovyMethods.getAt
train
public static List getAt(Matcher self, Collection indices) { List result = new ArrayList(); for (Object value : indices) { if (value instanceof Range) { result.addAll(getAt(self, (Range) value)); } else { int idx = DefaultTypeTransformation.intUnbox(value); result.add(getAt(self, idx)); } } return result; }
java
{ "resource": "" }
q106
StringGroovyMethods.getAt
train
public static String getAt(String text, int index) { index = normaliseIndex(index, text.length()); return text.substring(index, index + 1); }
java
{ "resource": "" }
q107
StringGroovyMethods.getAt
train
public static String getAt(String text, IntRange range) { return getAt(text, (Range) range); }
java
{ "resource": "" }
q108
StringGroovyMethods.getAt
train
public static String getAt(String text, Range range) { RangeInfo info = subListBorders(text.length(), range); String answer = text.substring(info.from, info.to); if (info.reverse) { answer = reverse(answer); } return answer; }
java
{ "resource": "" }
q109
StringGroovyMethods.getCount
train
public static int getCount(Matcher matcher) { int counter = 0; matcher.reset(); while (matcher.find()) { counter++; } return counter; }
java
{ "resource": "" }
q110
StringGroovyMethods.isAllWhitespace
train
public static boolean isAllWhitespace(CharSequence self) { String s = self.toString(); for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) return false; } return true; }
java
{ "resource": "" }
q111
StringGroovyMethods.isBigDecimal
train
public static boolean isBigDecimal(CharSequence self) { try { new BigDecimal(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q112
StringGroovyMethods.isBigInteger
train
public static boolean isBigInteger(CharSequence self) { try { new BigInteger(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q113
StringGroovyMethods.isDouble
train
public static boolean isDouble(CharSequence self) { try { Double.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q114
StringGroovyMethods.isFloat
train
public static boolean isFloat(CharSequence self) { try { Float.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q115
StringGroovyMethods.isInteger
train
public static boolean isInteger(CharSequence self) { try { Integer.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q116
StringGroovyMethods.isLong
train
public static boolean isLong(CharSequence self) { try { Long.valueOf(self.toString().trim()); return true; } catch (NumberFormatException nfe) { return false; } }
java
{ "resource": "" }
q117
StringGroovyMethods.leftShift
train
public static StringBuffer leftShift(String self, Object value) { return new StringBuffer(self).append(value); }
java
{ "resource": "" }
q118
StringGroovyMethods.leftShift
train
public static StringBuilder leftShift(StringBuilder self, Object value) { self.append(value); return self; }
java
{ "resource": "" }
q119
StringGroovyMethods.minus
train
public static String minus(CharSequence self, Object target) { String s = self.toString(); String text = DefaultGroovyMethods.toString(target); int index = s.indexOf(text); if (index == -1) return s; int end = index + text.length(); if (s.length() > end) { return s.substring(0, index) + s.substring(end); } return s.substring(0, index); }
java
{ "resource": "" }
q120
StringGroovyMethods.minus
train
public static String minus(CharSequence self, Pattern pattern) { return pattern.matcher(self).replaceFirst(""); }
java
{ "resource": "" }
q121
StringGroovyMethods.multiply
train
public static String multiply(CharSequence self, Number factor) { String s = self.toString(); int size = factor.intValue(); if (size == 0) return ""; else if (size < 0) { throw new IllegalArgumentException("multiply() should be called with a number of 0 or greater not: " + size); } StringBuilder answer = new StringBuilder(s); for (int i = 1; i < size; i++) { answer.append(s); } return answer.toString(); }
java
{ "resource": "" }
q122
StringGroovyMethods.next
train
public static String next(CharSequence self) { StringBuilder buffer = new StringBuilder(self); if (buffer.length() == 0) { buffer.append(Character.MIN_VALUE); } else { char last = buffer.charAt(buffer.length() - 1); if (last == Character.MAX_VALUE) { buffer.append(Character.MIN_VALUE); } else { char next = last; next++; buffer.setCharAt(buffer.length() - 1, next); } } return buffer.toString(); }
java
{ "resource": "" }
q123
StringGroovyMethods.normalize
train
public static String normalize(final CharSequence self) { final String s = self.toString(); int nx = s.indexOf('\r'); if (nx < 0) { return s; } final int len = s.length(); final StringBuilder sb = new StringBuilder(len); int i = 0; do { sb.append(s, i, nx); sb.append('\n'); if ((i = nx + 1) >= len) break; if (s.charAt(i) == '\n') { // skip the LF in CR LF if (++i >= len) break; } nx = s.indexOf('\r', i); } while (nx > 0); sb.append(s, i, len); return sb.toString(); }
java
{ "resource": "" }
q124
StringGroovyMethods.plus
train
public static String plus(CharSequence left, Object value) { return left + DefaultGroovyMethods.toString(value); }
java
{ "resource": "" }
q125
StringGroovyMethods.plus
train
public static String plus(Number value, String right) { return DefaultGroovyMethods.toString(value) + right; }
java
{ "resource": "" }
q126
StringGroovyMethods.readLines
train
public static List<String> readLines(CharSequence self) throws IOException { return IOGroovyMethods.readLines(new StringReader(self.toString())); }
java
{ "resource": "" }
q127
StringGroovyMethods.replaceAll
train
public static String replaceAll(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceAll(regex.toString(), replacement.toString()); }
java
{ "resource": "" }
q128
StringGroovyMethods.replaceFirst
train
public static String replaceFirst(final CharSequence self, final CharSequence regex, final CharSequence replacement) { return self.toString().replaceFirst(regex.toString(), replacement.toString()); }
java
{ "resource": "" }
q129
StringGroovyMethods.setIndex
train
public static void setIndex(Matcher matcher, int idx) { int count = getCount(matcher); if (idx < -count || idx >= count) { throw new IndexOutOfBoundsException("index is out of range " + (-count) + ".." + (count - 1) + " (index = " + idx + ")"); } if (idx == 0) { matcher.reset(); } else if (idx > 0) { matcher.reset(); for (int i = 0; i < idx; i++) { matcher.find(); } } else if (idx < 0) { matcher.reset(); idx += getCount(matcher); for (int i = 0; i < idx; i++) { matcher.find(); } } }
java
{ "resource": "" }
q130
StringGroovyMethods.splitEachLine
train
public static <T> T splitEachLine(CharSequence self, CharSequence regex, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(self, Pattern.compile(regex.toString()), closure); }
java
{ "resource": "" }
q131
StringGroovyMethods.splitEachLine
train
public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { final List<String> list = readLines(self); T result = null; for (String line : list) { List vals = Arrays.asList(pattern.split(line)); result = closure.call(vals); } return result; }
java
{ "resource": "" }
q132
StringGroovyMethods.takeWhile
train
public static String takeWhile(GString self, @ClosureParams(value=SimpleType.class, options="char") Closure condition) { return (String) takeWhile(self.toString(), condition); }
java
{ "resource": "" }
q133
StringGroovyMethods.toList
train
public static List<String> toList(CharSequence self) { String s = self.toString(); int size = s.length(); List<String> answer = new ArrayList<String>(size); for (int i = 0; i < size; i++) { answer.add(s.substring(i, i + 1)); } return answer; }
java
{ "resource": "" }
q134
StringGroovyMethods.unexpand
train
public static String unexpand(CharSequence self, int tabStop) { String s = self.toString(); if (s.length() == 0) return s; try { StringBuilder builder = new StringBuilder(); for (String line : readLines((CharSequence) s)) { builder.append(unexpandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!s.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return s; }
java
{ "resource": "" }
q135
StringGroovyMethods.unexpandLine
train
public static String unexpandLine(CharSequence self, int tabStop) { StringBuilder builder = new StringBuilder(self.toString()); int index = 0; while (index + tabStop < builder.length()) { // cut original string in tabstop-length pieces String piece = builder.substring(index, index + tabStop); // count trailing whitespace characters int count = 0; while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1))))) count++; // replace if whitespace was found if (count > 0) { piece = piece.substring(0, tabStop - count) + '\t'; builder.replace(index, index + tabStop, piece); index = index + tabStop - (count - 1); } else index = index + tabStop; } return builder.toString(); }
java
{ "resource": "" }
q136
ClassNode.hasPossibleMethod
train
public boolean hasPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } ClassNode node = this; do { for (MethodNode method : getMethods(name)) { if (method.getParameters().length == count && !method.isStatic()) { return true; } } node = node.getSuperClass(); } while (node != null); return false; }
java
{ "resource": "" }
q137
StaticTypeCheckingVisitor.checkOrMarkPrivateAccess
train
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) { if (fn!=null && Modifier.isPrivate(fn.getModifiers()) && (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) && fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) { addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn); } }
java
{ "resource": "" }
q138
StaticTypeCheckingVisitor.checkOrMarkPrivateAccess
train
private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) { if (mn==null) { return; } ClassNode declaringClass = mn.getDeclaringClass(); ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode(); if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) { int mods = mn.getModifiers(); boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule(); String packageName = declaringClass.getPackageName(); if (packageName==null) { packageName = ""; } if ((Modifier.isPrivate(mods) && sameModule) || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) { addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn); } } }
java
{ "resource": "" }
q139
StaticTypeCheckingVisitor.ensureValidSetter
train
private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) { // for expressions like foo = { ... } // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo VariableExpression ve = new VariableExpression("%", setterInfo.receiverType); MethodCallExpression call = new MethodCallExpression( ve, setterInfo.name, rightExpression ); call.setImplicitThis(false); visitMethodCallExpression(call); MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate==null) { // this may happen if there's a setter of type boolean/String/Class, and that we are using the property // notation AND that the RHS is not a boolean/String/Class for (MethodNode setter : setterInfo.setters) { ClassNode type = getWrapper(setter.getParameters()[0].getOriginType()); if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) { call = new MethodCallExpression( ve, setterInfo.name, new CastExpression(type,rightExpression) ); call.setImplicitThis(false); visitMethodCallExpression(call); directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate!=null) { break; } } } } if (directSetterCandidate != null) { for (MethodNode setter : setterInfo.setters) { if (setter == directSetterCandidate) { leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate); storeType(leftExpression, getType(rightExpression)); break; } } } else { ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType(); addAssignmentError(firstSetterType, getType(rightExpression), expression); return true; } return false; }
java
{ "resource": "" }
q140
StaticTypeCheckingVisitor.addArrayMethods
train
private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) { if (args.length!=1) return; if (!receiver.isArray()) return; if (!isIntCategory(getUnwrapper(args[0]))) return; if ("getAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } else if ("setAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } }
java
{ "resource": "" }
q141
StaticTypeCheckingVisitor.getGenericsResolvedTypeOfFieldOrProperty
train
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
java
{ "resource": "" }
q142
EncodingGroovyMethods.decodeBase64
train
public static byte[] decodeBase64(String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift-- != 4) { buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift--; done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } }
java
{ "resource": "" }
q143
Groovy.runStatements
train
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
java
{ "resource": "" }
q144
JsonOutput.toJson
train
public static String toJson(Date date) { if (date == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(date, buffer); return buffer.toString(); }
java
{ "resource": "" }
q145
JsonOutput.toJson
train
public static String toJson(Calendar cal) { if (cal == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(cal.getTime(), buffer); return buffer.toString(); }
java
{ "resource": "" }
q146
JsonOutput.writeNumber
train
private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) { if (numberClass == Integer.class) { buffer.addInt((Integer) value); } else if (numberClass == Long.class) { buffer.addLong((Long) value); } else if (numberClass == BigInteger.class) { buffer.addBigInteger((BigInteger) value); } else if (numberClass == BigDecimal.class) { buffer.addBigDecimal((BigDecimal) value); } else if (numberClass == Double.class) { Double doubleValue = (Double) value; if (doubleValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (doubleValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addDouble(doubleValue); } else if (numberClass == Float.class) { Float floatValue = (Float) value; if (floatValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (floatValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addFloat(floatValue); } else if (numberClass == Byte.class) { buffer.addByte((Byte) value); } else if (numberClass == Short.class) { buffer.addShort((Short) value); } else { // Handle other Number implementations buffer.addString(value.toString()); } }
java
{ "resource": "" }
q147
JsonOutput.writeCharSequence
train
private static void writeCharSequence(CharSequence seq, CharBuf buffer) { if (seq.length() > 0) { buffer.addJsonEscapedString(seq.toString()); } else { buffer.addChars(EMPTY_STRING_CHARS); } }
java
{ "resource": "" }
q148
ShortTypeHandling.castToEnum
train
public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
java
{ "resource": "" }
q149
Groovyc.setTargetBytecode
train
public void setTargetBytecode(String version) { if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) { this.targetBytecode = version; } }
java
{ "resource": "" }
q150
Node.depthFirst
train
public List depthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(depthFirstRest()); return answer; }
java
{ "resource": "" }
q151
MetaProperty.getGetterName
train
public static String getGetterName(String propertyName, Class type) { String prefix = type == boolean.class || type == Boolean.class ? "is" : "get"; return prefix + MetaClassHelper.capitalize(propertyName); }
java
{ "resource": "" }
q152
ProxyMetaClass.getInstance
train
public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new ProxyMetaClass(metaRegistry, theClass, meta); }
java
{ "resource": "" }
q153
ResolveVisitor.correctClassClassChain
train
private Expression correctClassClassChain(PropertyExpression pe) { LinkedList<Expression> stack = new LinkedList<Expression>(); ClassExpression found = null; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof ClassExpression) { found = (ClassExpression) it; break; } else if (!(it.getClass() == PropertyExpression.class)) { return pe; } stack.addFirst(it); } if (found == null) return pe; if (stack.isEmpty()) return pe; Object stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpression = (PropertyExpression) stackElement; String propertyNamePart = classPropertyExpression.getPropertyAsString(); if (propertyNamePart == null || !propertyNamePart.equals("class")) return pe; found.setSourcePosition(classPropertyExpression); if (stack.isEmpty()) return found; stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement; classPropertyExpressionContainer.setObjectExpression(found); return pe; }
java
{ "resource": "" }
q154
DefaultGroovyMethodsSupport.closeWithWarning
train
public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } }
java
{ "resource": "" }
q155
ManagedConcurrentValueMap.get
train
public V get(K key) { ManagedReference<V> ref = internalMap.get(key); if (ref!=null) return ref.get(); return null; }
java
{ "resource": "" }
q156
ManagedConcurrentValueMap.put
train
public void put(final K key, V value) { ManagedReference<V> ref = new ManagedReference<V>(bundle, value) { @Override public void finalizeReference() { super.finalizeReference(); internalMap.remove(key, get()); } }; internalMap.put(key, ref); }
java
{ "resource": "" }
q157
SourceUnit.getSample
train
public String getSample(int line, int column, Janitor janitor) { String sample = null; String text = source.getLine(line, janitor); if (text != null) { if (column > 0) { String marker = Utilities.repeatString(" ", column - 1) + "^"; if (column > 40) { int start = column - 30 - 1; int end = (column + 10 > text.length() ? text.length() : column + 10 - 1); sample = " " + text.substring(start, end) + Utilities.eol() + " " + marker.substring(start, marker.length()); } else { sample = " " + text + Utilities.eol() + " " + marker; } } else { sample = text; } } return sample; }
java
{ "resource": "" }
q158
Sql.withInstance
train
public static void withInstance(String url, Closure c) throws SQLException { Sql sql = null; try { sql = newInstance(url); c.call(sql); } finally { if (sql != null) sql.close(); } }
java
{ "resource": "" }
q159
Sql.withTransaction
train
public synchronized void withTransaction(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; boolean savedAutoCommit = true; try { connection = createConnection(); savedAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); callClosurePossiblyWithConnection(closure, connection); connection.commit(); } catch (SQLException e) { handleError(connection, e); throw e; } catch (RuntimeException e) { handleError(connection, e); throw e; } catch (Error e) { handleError(connection, e); throw e; } catch (Exception e) { handleError(connection, e); throw new SQLException("Unexpected exception during transaction", e); } finally { if (connection != null) { try { connection.setAutoCommit(savedAutoCommit); } catch (SQLException e) { LOG.finest("Caught exception resetting auto commit: " + e.getMessage() + " - continuing"); } } cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } }
java
{ "resource": "" }
q160
ReflectionMethodInvoker.invoke
train
public static Object invoke(Object object, String methodName, Object[] parameters) { try { Class[] classTypes = new Class[parameters.length]; for (int i = 0; i < classTypes.length; i++) { classTypes[i] = parameters[i].getClass(); } Method method = object.getClass().getMethod(methodName, classTypes); return method.invoke(object, parameters); } catch (Throwable t) { return InvokerHelper.invokeMethod(object, methodName, parameters); } }
java
{ "resource": "" }
q161
StringHelper.tokenizeUnquoted
train
public static String[] tokenizeUnquoted(String s) { List tokens = new LinkedList(); int first = 0; while (first < s.length()) { first = skipWhitespace(s, first); int last = scanToken(s, first); if (first < last) { tokens.add(s.substring(first, last)); } first = last; } return (String[])tokens.toArray(new String[tokens.size()]); }
java
{ "resource": "" }
q162
StaticCompilationVisitor.addPrivateFieldsAccessors
train
@SuppressWarnings("unchecked") private void addPrivateFieldsAccessors(ClassNode node) { Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS); if (accessedFields==null) return; Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS); if (privateConstantAccessors!=null) { // already added return; } int acc = -1; privateConstantAccessors = new HashMap<String, MethodNode>(); final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC; for (FieldNode fieldNode : node.getFields()) { if (accessedFields.contains(fieldNode)) { acc++; Parameter param = new Parameter(node.getPlainNodeReference(), "$that"); Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param); Statement stmt = new ExpressionStatement(new PropertyExpression( receiver, fieldNode.getName() )); MethodNode accessor = node.addMethod("pfaccess$"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt); privateConstantAccessors.put(fieldNode.getName(), accessor); } } node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors); }
java
{ "resource": "" }
q163
CompilerConfiguration.isPostJDK5
train
public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); }
java
{ "resource": "" }
q164
CompilerConfiguration.setTargetDirectory
train
public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } }
java
{ "resource": "" }
q165
RootLoader.loadClass
train
protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); } catch (ClassNotFoundException cnfe) { // IGNORE } if (c == null) c = super.loadClass(name, resolve); if (resolve) resolveClass(c); return c; }
java
{ "resource": "" }
q166
NodeList.getAt
train
public NodeList getAt(String name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; Object temp = childNode.get(name); if (temp instanceof Collection) { answer.addAll((Collection) temp); } else { answer.add(temp); } } } return answer; }
java
{ "resource": "" }
q167
NodeList.text
train
public String text() { String previousText = null; StringBuilder buffer = null; for (Object child : this) { String text = null; if (child instanceof String) { text = (String) child; } else if (child instanceof Node) { text = ((Node) child).text(); } if (text != null) { if (previousText == null) { previousText = text; } else { if (buffer == null) { buffer = new StringBuilder(); buffer.append(previousText); } buffer.append(text); } } } if (buffer != null) { return buffer.toString(); } if (previousText != null) { return previousText; } return ""; }
java
{ "resource": "" }
q168
Parser.isAllNumeric
train
private boolean isAllNumeric(TokenStream stream) { List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens(); for(Token token:tokens) { try { Integer.parseInt(token.getText()); } catch(NumberFormatException e) { return false; } } return true; }
java
{ "resource": "" }
q169
Parser.collectTokenStreams
train
private List<TokenStream> collectTokenStreams(TokenStream stream) { // walk through the token stream and build a collection // of sub token streams that represent possible date locations List<Token> currentGroup = null; List<List<Token>> groups = new ArrayList<List<Token>>(); Token currentToken; int currentTokenType; StringBuilder tokenString = new StringBuilder(); while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) { currentTokenType = currentToken.getType(); tokenString.append(DateParser.tokenNames[currentTokenType]).append(" "); // we're currently NOT collecting for a possible date group if(currentGroup == null) { // skip over white space and known tokens that cannot be the start of a date if(currentTokenType != DateLexer.WHITE_SPACE && DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) { currentGroup = new ArrayList<Token>(); currentGroup.add(currentToken); } } // we're currently collecting else { // preserve white space if(currentTokenType == DateLexer.WHITE_SPACE) { currentGroup.add(currentToken); } else { // if this is an unknown token, we'll close out the current group if(currentTokenType == DateLexer.UNKNOWN) { addGroup(currentGroup, groups); currentGroup = null; } // otherwise, the token is known and we're currently collecting for // a group, so we'll add it to the current group else { currentGroup.add(currentToken); } } } } if(currentGroup != null) { addGroup(currentGroup, groups); } _logger.info("STREAM: " + tokenString.toString()); List<TokenStream> streams = new ArrayList<TokenStream>(); for(List<Token> group:groups) { if(!group.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("GROUP: "); for (Token token : group) { builder.append(DateParser.tokenNames[token.getType()]).append(" "); } _logger.info(builder.toString()); streams.add(new CommonTokenStream(new NattyTokenSource(group))); } } return streams; }
java
{ "resource": "" }
q170
Parser.addGroup
train
private void addGroup(List<Token> group, List<List<Token>> groups) { if(group.isEmpty()) return; // remove trailing tokens that should be ignored while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains( group.get(group.size() - 1).getType())) { group.remove(group.size() - 1); } // if the group still has some tokens left, we'll add it to our list of groups if(!group.isEmpty()) { groups.add(group); } }
java
{ "resource": "" }
q171
WalkerState.seekToDayOfWeek
train
public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) { int dayOfWeekInt = Integer.parseInt(dayOfWeek); int seekAmountInt = Integer.parseInt(seekAmount); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK)); assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7); markDateInvocation(); int sign = direction.equals(DIR_RIGHT) ? 1 : -1; if(seekType.equals(SEEK_BY_WEEK)) { // set our calendar to this weeks requested day of the week, // then add or subtract the week(s) _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt); _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign); } else if(seekType.equals(SEEK_BY_DAY)) { // find the closest day do { _calendar.add(Calendar.DAY_OF_YEAR, sign); } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt); // now add/subtract any additional days if(seekAmountInt > 0) { _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign); } } }
java
{ "resource": "" }
q172
WalkerState.seekToDayOfMonth
train
public void seekToDayOfMonth(String dayOfMonth) { int dayOfMonthInt = Integer.parseInt(dayOfMonth); assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31); markDateInvocation(); dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt); }
java
{ "resource": "" }
q173
WalkerState.seekToDayOfYear
train
public void seekToDayOfYear(String dayOfYear) { int dayOfYearInt = Integer.parseInt(dayOfYear); assert(dayOfYearInt >= 1 && dayOfYearInt <= 366); markDateInvocation(); dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt); }
java
{ "resource": "" }
q174
WalkerState.seekToMonth
train
public void seekToMonth(String direction, String seekAmount, String month) { int seekAmountInt = Integer.parseInt(seekAmount); int monthInt = Integer.parseInt(month); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(monthInt >= 1 && monthInt <= 12); markDateInvocation(); // set the day to the first of month. This step is necessary because if we seek to the // current day of a month whose number of days is less than the current day, we will // pushed into the next month. _calendar.set(Calendar.DAY_OF_MONTH, 1); // seek to the appropriate year if(seekAmountInt > 0) { int currentMonth = _calendar.get(Calendar.MONTH) + 1; int sign = direction.equals(DIR_RIGHT) ? 1 : -1; int numYearsToShift = seekAmountInt + (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1)); _calendar.add(Calendar.YEAR, (numYearsToShift * sign)); } // now set the month _calendar.set(Calendar.MONTH, monthInt - 1); }
java
{ "resource": "" }
q175
WalkerState.setExplicitTime
train
public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) { int hoursInt = Integer.parseInt(hours); int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0; assert(amPm == null || amPm.equals(AM) || amPm.equals(PM)); assert(hoursInt >= 0); assert(minutesInt >= 0 && minutesInt < 60); markTimeInvocation(amPm); // reset milliseconds to 0 _calendar.set(Calendar.MILLISECOND, 0); // if no explicit zone is given, we use our own TimeZone zone = null; if(zoneString != null) { if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) { zoneString = GMT + zoneString; } zone = TimeZone.getTimeZone(zoneString); } _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone); _calendar.set(Calendar.HOUR_OF_DAY, hoursInt); // hours greater than 12 are in 24-hour time if(hoursInt <= 12) { int amPmInt = amPm == null ? (hoursInt >= 12 ? Calendar.PM : Calendar.AM) : amPm.equals(PM) ? Calendar.PM : Calendar.AM; _calendar.set(Calendar.AM_PM, amPmInt); // calendar is whacky at 12 o'clock (must use 0) if(hoursInt == 12) hoursInt = 0; _calendar.set(Calendar.HOUR, hoursInt); } if(seconds != null) { int secondsInt = Integer.parseInt(seconds); assert(secondsInt >= 0 && secondsInt < 60); _calendar.set(Calendar.SECOND, secondsInt); } else { _calendar.set(Calendar.SECOND, 0); } _calendar.set(Calendar.MINUTE, minutesInt); }
java
{ "resource": "" }
q176
WalkerState.seekToHoliday
train
public void seekToHoliday(String holidayString, String direction, String seekAmount) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount); }
java
{ "resource": "" }
q177
WalkerState.seekToHolidayYear
train
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
java
{ "resource": "" }
q178
WalkerState.seekToSeason
train
public void seekToSeason(String seasonString, String direction, String seekAmount) { Season season = Season.valueOf(seasonString); assert(season!= null); seekToIcsEvent(SEASON_ICS_FILE, season.getSummary(), direction, seekAmount); }
java
{ "resource": "" }
q179
WalkerState.seekToSeasonYear
train
public void seekToSeasonYear(String seasonString, String yearString) { Season season = Season.valueOf(seasonString); assert(season != null); seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary()); }
java
{ "resource": "" }
q180
WalkerState.resetCalendar
train
private void resetCalendar() { _calendar = getCalendar(); if (_defaultTimeZone != null) { _calendar.setTimeZone(_defaultTimeZone); } _currentYear = _calendar.get(Calendar.YEAR); }
java
{ "resource": "" }
q181
WalkerState.seasonalDateFromIcs
train
private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) { Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year); return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0)); }
java
{ "resource": "" }
q182
WalkerState.markDateInvocation
train
private void markDateInvocation() { _updatePreviousDates = !_dateGivenInGroup; _dateGivenInGroup = true; _dateGroup.setDateInferred(false); if(_firstDateInvocationInGroup) { // if a time has been given within the current date group, // we capture the current time before resetting the calendar if(_timeGivenInGroup) { int hours = _calendar.get(Calendar.HOUR_OF_DAY); int minutes = _calendar.get(Calendar.MINUTE); int seconds = _calendar.get(Calendar.SECOND); resetCalendar(); _calendar.set(Calendar.HOUR_OF_DAY, hours); _calendar.set(Calendar.MINUTE, minutes); _calendar.set(Calendar.SECOND, seconds); } else { resetCalendar(); } _firstDateInvocationInGroup = false; } }
java
{ "resource": "" }
q183
HistQuotesRequest.cleanHistCalendar
train
private Calendar cleanHistCalendar(Calendar cal) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); return cal; }
java
{ "resource": "" }
q184
Utils.parseDividendDate
train
public static Calendar parseDividendDate(String date) { if (!Utils.isParseable(date)) { return null; } date = date.trim(); SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US); format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); try { Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); parsedDate.setTime(format.parse(date)); if (parsedDate.get(Calendar.YEAR) == 1970) { // Not really clear which year the dividend date is... making a reasonable guess. int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH); int year = today.get(Calendar.YEAR); if (monthDiff > 6) { year -= 1; } else if (monthDiff < -6) { year += 1; } parsedDate.set(Calendar.YEAR, year); } return parsedDate; } catch (ParseException ex) { log.warn("Failed to parse dividend date: " + date); log.debug("Failed to parse dividend date: " + date, ex); return null; } }
java
{ "resource": "" }
q185
ExchangeTimeZone.get
train
public static TimeZone get(String suffix) { if(SUFFIX_TIMEZONES.containsKey(suffix)) { return SUFFIX_TIMEZONES.get(suffix); } log.warn("Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York", suffix); return SUFFIX_TIMEZONES.get(""); }
java
{ "resource": "" }
q186
ExchangeTimeZone.getStockTimeZone
train
public static TimeZone getStockTimeZone(String symbol) { // First check if it's a known stock index if(INDEX_TIMEZONES.containsKey(symbol)) { return INDEX_TIMEZONES.get(symbol); } if(!symbol.contains(".")) { return ExchangeTimeZone.get(""); } String[] split = symbol.split("\\."); return ExchangeTimeZone.get(split[split.length - 1]); }
java
{ "resource": "" }
q187
VideoRendererBuilder.getPrototypeClass
train
@Override protected Class getPrototypeClass(Video content) { Class prototypeClass; if (content.isFavorite()) { prototypeClass = FavoriteVideoRenderer.class; } else if (content.isLive()) { prototypeClass = LiveVideoRenderer.class; } else { prototypeClass = LikeVideoRenderer.class; } return prototypeClass; }
java
{ "resource": "" }
q188
RVRendererAdapter.getItemViewType
train
@Override public int getItemViewType(int position) { T content = getItem(position); return rendererBuilder.getItemViewType(content); }
java
{ "resource": "" }
q189
RVRendererAdapter.onCreateViewHolder
train
@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { rendererBuilder.withParent(viewGroup); rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext())); rendererBuilder.withViewType(viewType); RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder(); if (viewHolder == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null viewHolder"); } return viewHolder; }
java
{ "resource": "" }
q190
RVRendererAdapter.onBindViewHolder
train
@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) { T content = getItem(position); Renderer<T> renderer = viewHolder.getRenderer(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null renderer"); } renderer.setContent(content); updateRendererExtraValues(content, renderer, position); renderer.render(); }
java
{ "resource": "" }
q191
RVRendererAdapter.diffUpdate
train
public void diffUpdate(List<T> newList) { if (getCollection().size() == 0) { addAll(newList); notifyDataSetChanged(); } else { DiffCallback diffCallback = new DiffCallback(collection, newList); DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback); clear(); addAll(newList); diffResult.dispatchUpdatesTo(this); } }
java
{ "resource": "" }
q192
RendererBuilder.withPrototype
train
public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) { if (renderer == null) { throw new NeedsPrototypesException( "RendererBuilder can't use a null Renderer<T> instance as prototype"); } this.prototypes.add(renderer); return this; }
java
{ "resource": "" }
q193
RendererBuilder.bind
train
public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) { if (clazz == null || prototype == null) { throw new IllegalArgumentException( "The binding RecyclerView binding can't be configured using null instances"); } prototypes.add(prototype); binding.put(clazz, prototype.getClass()); return this; }
java
{ "resource": "" }
q194
RendererBuilder.getItemViewType
train
int getItemViewType(T content) { Class prototypeClass = getPrototypeClass(content); validatePrototypeClass(prototypeClass); return getItemViewType(prototypeClass); }
java
{ "resource": "" }
q195
RendererBuilder.build
train
protected Renderer build() { validateAttributes(); Renderer renderer; if (isRecyclable(convertView, content)) { renderer = recycle(convertView, content); } else { renderer = createRenderer(content, parent); } return renderer; }
java
{ "resource": "" }
q196
RendererBuilder.buildRendererViewHolder
train
protected RendererViewHolder buildRendererViewHolder() { validateAttributesToCreateANewRendererViewHolder(); Renderer renderer = getPrototypeByIndex(viewType).copy(); renderer.onCreate(null, layoutInflater, parent); return new RendererViewHolder(renderer); }
java
{ "resource": "" }
q197
RendererBuilder.recycle
train
private Renderer recycle(View convertView, T content) { Renderer renderer = (Renderer) convertView.getTag(); renderer.onRecycle(content); return renderer; }
java
{ "resource": "" }
q198
RendererBuilder.createRenderer
train
private Renderer createRenderer(T content, ViewGroup parent) { int prototypeIndex = getPrototypeIndex(content); Renderer renderer = getPrototypeByIndex(prototypeIndex).copy(); renderer.onCreate(content, layoutInflater, parent); return renderer; }
java
{ "resource": "" }
q199
RendererBuilder.getPrototypeByIndex
train
private Renderer getPrototypeByIndex(final int prototypeIndex) { Renderer prototypeSelected = null; int i = 0; for (Renderer prototype : prototypes) { if (i == prototypeIndex) { prototypeSelected = prototype; } i++; } return prototypeSelected; }
java
{ "resource": "" }